diff --git a/Examples/benchmarker/Program.cs b/Examples/benchmarker/Program.cs index e07cc6bb..c7f00f27 100644 --- a/Examples/benchmarker/Program.cs +++ b/Examples/benchmarker/Program.cs @@ -8,207 +8,230 @@ using BenchmarkDotNet.Running; using Microsoft.EntityFrameworkCore; //using SqlSugar; -namespace FreeSql.Bechmarker { +namespace FreeSql.Bechmarker +{ - public class Program { - public static void Main(string[] args) { - var summaryInsert = BenchmarkRunner.Run(); - var summarySelect = BenchmarkRunner.Run(); - var summaryUpdate = BenchmarkRunner.Run(); - } - } + public class Program + { + public static void Main(string[] args) + { + var summaryInsert = BenchmarkRunner.Run(); + var summarySelect = BenchmarkRunner.Run(); + var summaryUpdate = BenchmarkRunner.Run(); + } + } - public class Orm { - public static IFreeSql fsql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20") - //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=20") - .UseAutoSyncStructure(false) - .UseNoneCommandParameter(true) - //.UseConfigEntityFromDbFirst(true) - .Build(); + public class Orm + { + public static IFreeSql fsql = new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20") + //.UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=20") + .UseAutoSyncStructure(false) + .UseNoneCommandParameter(true) + //.UseConfigEntityFromDbFirst(true) + .Build(); - //public static SqlSugarClient sugar { - // get => new SqlSugarClient(new ConnectionConfig() { - // //不欺负,让连接池100个最小 - // ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20", - // DbType = DbType.SqlServer, - // //ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20", - // //DbType = DbType.MySql, - // IsAutoCloseConnection = true, - // InitKeyType = InitKeyType.Attribute - // }); - //} - } - class SongContext : DbContext { - public DbSet Songs { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21"); - //optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21"); - } - } + //public static SqlSugarClient sugar { + // get => new SqlSugarClient(new ConnectionConfig() { + // //不欺负,让连接池100个最小 + // ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20", + // DbType = DbType.SqlServer, + // //ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20", + // //DbType = DbType.MySql, + // IsAutoCloseConnection = true, + // InitKeyType = InitKeyType.Attribute + // }); + //} + } + class SongContext : DbContext + { + public DbSet Songs { get; set; } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21"); + //optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21"); + } + } - [CoreJob] - [RPlotExporter, RankColumn] - public class OrmVsInsert { - public IEnumerable songs; + [CoreJob] + [RPlotExporter, RankColumn] + public class OrmVsInsert + { + public IEnumerable songs; - [Params(1, 500, 1000, 5000, 10000, 50000, 100000)] - public int size; + [Params(1, 500, 1000, 5000, 10000, 50000, 100000)] + public int size; - [GlobalSetup] - public void Setup() { - Orm.fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag)); - //Orm.sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag)); - //sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements + [GlobalSetup] + public void Setup() + { + Orm.fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag)); + //Orm.sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag)); + //sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements - //测试前清空数据 - Orm.fsql.Delete().Where(a => a.Id > 0).ExecuteAffrows(); - //Orm.sugar.Deleteable().Where(a => a.Id > 0).ExecuteCommand(); - Orm.fsql.Ado.ExecuteNonQuery("delete from efcore_song"); + //测试前清空数据 + Orm.fsql.Delete().Where(a => a.Id > 0).ExecuteAffrows(); + //Orm.sugar.Deleteable().Where(a => a.Id > 0).ExecuteCommand(); + Orm.fsql.Ado.ExecuteNonQuery("delete from efcore_song"); - songs = Enumerable.Range(0, size).Select(a => new Song { - Create_time = DateTime.Now, - Is_deleted = false, - Title = $"Insert_{a}", - Url = $"Url_{a}" - }); + songs = Enumerable.Range(0, size).Select(a => new Song + { + Create_time = DateTime.Now, + Is_deleted = false, + Title = $"Insert_{a}", + Url = $"Url_{a}" + }); - //预热 - Orm.fsql.Insert(songs.First()).ExecuteAffrows(); - //Orm.sugar.Insertable(songs.First()).ExecuteCommand(); - using (var db = new SongContext()) { - //db.Configuration.AutoDetectChangesEnabled = false; - db.Songs.AddRange(songs.First()); - db.SaveChanges(); - } - } + //预热 + Orm.fsql.Insert(songs.First()).ExecuteAffrows(); + //Orm.sugar.Insertable(songs.First()).ExecuteCommand(); + using (var db = new SongContext()) + { + //db.Configuration.AutoDetectChangesEnabled = false; + db.Songs.AddRange(songs.First()); + db.SaveChanges(); + } + } - [Benchmark] - public int FreeSqlInsert() => Orm.fsql.Insert(songs).ExecuteAffrows(); + [Benchmark] + public int FreeSqlInsert() => Orm.fsql.Insert(songs).ExecuteAffrows(); - //[Benchmark] - //public int SqlSugarInsert() => Orm.sugar.Insertable(songs.ToArray()).ExecuteCommand(); + //[Benchmark] + //public int SqlSugarInsert() => Orm.sugar.Insertable(songs.ToArray()).ExecuteCommand(); - [Benchmark] - public int EfCoreInsert() { - using (var db = new SongContext()) { - //db.Configuration.AutoDetectChangesEnabled = false; - db.Songs.AddRange(songs.ToArray()); - return db.SaveChanges(); - } - } - } + [Benchmark] + public int EfCoreInsert() + { + using (var db = new SongContext()) + { + //db.Configuration.AutoDetectChangesEnabled = false; + db.Songs.AddRange(songs.ToArray()); + return db.SaveChanges(); + } + } + } - [CoreJob] - [RPlotExporter, RankColumn] - public class OrmVsUpdate { - public List songs; + [CoreJob] + [RPlotExporter, RankColumn] + public class OrmVsUpdate + { + public List songs; - [Params(1, 500, 1000, 5000, 10000, 50000, 100000)] - public int size; + [Params(1, 500, 1000, 5000, 10000, 50000, 100000)] + public int size; - [GlobalSetup] - public void Setup() { - songs = Orm.fsql.Select().Limit(size).ToList(); - } + [GlobalSetup] + public void Setup() + { + songs = Orm.fsql.Select().Limit(size).ToList(); + } - [Benchmark] - public int FreeSqlUpdate() => Orm.fsql.Update().SetSource(songs).ExecuteAffrows(); + [Benchmark] + public int FreeSqlUpdate() => Orm.fsql.Update().SetSource(songs).ExecuteAffrows(); - //[Benchmark] - //public int SqlSugarUpdate() => Orm.sugar.Updateable(songs).ExecuteCommand(); + //[Benchmark] + //public int SqlSugarUpdate() => Orm.sugar.Updateable(songs).ExecuteCommand(); - [Benchmark] - public int EfCoreUpdate() { - using (var db = new SongContext()) { - //db.Configuration.AutoDetectChangesEnabled = false; - db.Songs.UpdateRange(songs.ToArray()); - return db.SaveChanges(); - } - } - } + [Benchmark] + public int EfCoreUpdate() + { + using (var db = new SongContext()) + { + //db.Configuration.AutoDetectChangesEnabled = false; + db.Songs.UpdateRange(songs.ToArray()); + return db.SaveChanges(); + } + } + } - [CoreJob] - [RPlotExporter, RankColumn] - public class OrmVsSelect { + [CoreJob] + [RPlotExporter, RankColumn] + public class OrmVsSelect + { - [Params(1, 500, 1000, 5000, 10000, 50000, 100000)] - public int size; + [Params(1, 500, 1000, 5000, 10000, 50000, 100000)] + public int size; - [GlobalSetup] - public void Setup() { - - } + [GlobalSetup] + public void Setup() + { - [Benchmark] - public List FreeSqlSelect() => Orm.fsql.Select().Limit(size).ToList(); + } - //[Benchmark] - //public List SqlSugarSelect() => Orm.sugar.Queryable().Take(size).ToList(); + [Benchmark] + public List FreeSqlSelect() => Orm.fsql.Select().Limit(size).ToList(); - [Benchmark] - public List EfCoreSelect() { - using (var db = new SongContext()) { - return db.Songs.Take(size).AsNoTracking().ToList(); - } - } - } + //[Benchmark] + //public List SqlSugarSelect() => Orm.sugar.Queryable().Take(size).ToList(); - [FreeSql.DataAnnotations.Table(Name = "freesql_song")] - //[SugarTable("sugar_song")] - [Table("efcore_song")] - public class Song { - [FreeSql.DataAnnotations.Column(IsIdentity = true)] - //[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] - [Key] - [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } + [Benchmark] + public List EfCoreSelect() + { + using (var db = new SongContext()) + { + return db.Songs.Take(size).AsNoTracking().ToList(); + } + } + } - //[SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual ICollection Tags { get; set; } - } - [FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")] - //[SugarTable("sugar_song_tag")] - [Table("efcore_song_tag")] - public class Song_tag { - public int Song_id { get; set; } - //[SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual Song Song { get; set; } + [FreeSql.DataAnnotations.Table(Name = "freesql_song")] + //[SugarTable("sugar_song")] + [Table("efcore_song")] + public class Song + { + [FreeSql.DataAnnotations.Column(IsIdentity = true)] + //[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } - public int Tag_id { get; set; } - //[SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual Tag Tag { get; set; } - } - [FreeSql.DataAnnotations.Table(Name = "freesql_tag")] - //[SugarTable("sugar_tag")] - [Table("efcore_tag")] - public class Tag { - [FreeSql.DataAnnotations.Column(IsIdentity = true)] - //[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] - [Key] - [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; set; } - public int? Parent_id { get; set; } - //[SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual Tag Parent { get; set; } + //[SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual ICollection Tags { get; set; } + } + [FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")] + //[SugarTable("sugar_song_tag")] + [Table("efcore_song_tag")] + public class Song_tag + { + public int Song_id { get; set; } + //[SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual Song Song { get; set; } - public decimal? Ddd { get; set; } - public string Name { get; set; } + public int Tag_id { get; set; } + //[SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual Tag Tag { get; set; } + } + [FreeSql.DataAnnotations.Table(Name = "freesql_tag")] + //[SugarTable("sugar_tag")] + [Table("efcore_tag")] + public class Tag + { + [FreeSql.DataAnnotations.Column(IsIdentity = true)] + //[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + public int? Parent_id { get; set; } + //[SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual Tag Parent { get; set; } - //[SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual ICollection Songs { get; set; } - //[SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual ICollection Tags { get; set; } - } + public decimal? Ddd { get; set; } + public string Name { get; set; } + + //[SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual ICollection Songs { get; set; } + //[SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual ICollection Tags { get; set; } + } } diff --git a/Examples/dbcontext_01/Controllers/ValuesController.cs b/Examples/dbcontext_01/Controllers/ValuesController.cs index 90252e03..8d8e4299 100644 --- a/Examples/dbcontext_01/Controllers/ValuesController.cs +++ b/Examples/dbcontext_01/Controllers/ValuesController.cs @@ -5,237 +5,251 @@ using System.Threading.Tasks; using FreeSql; using Microsoft.AspNetCore.Mvc; -namespace dbcontext_01.Controllers { - [Route("api/[controller]")] - [ApiController] - public class ValuesController : ControllerBase { - - IFreeSql _orm; - SongContext _songContext; - public ValuesController(SongContext songContext, - IFreeSql orm1, IFreeSql orm2, - IFreeSql orm3 - ) { - _songContext = songContext; - _orm = orm1; +namespace dbcontext_01.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class ValuesController : ControllerBase + { + + IFreeSql _orm; + SongContext _songContext; + public ValuesController(SongContext songContext, + IFreeSql orm1, IFreeSql orm2, + IFreeSql orm3 + ) + { + _songContext = songContext; + _orm = orm1; + + } + + // GET api/values + [HttpGet] + async public Task Get() + { + + long id = 0; + + try + { + + var repos2Song = _orm.GetRepository(); + repos2Song.Where(a => a.Id > 10).ToList(); + //查询结果,进入 states + + var song = new Song { }; + repos2Song.Insert(song); + id = song.Id; - } - - // GET api/values - [HttpGet] - async public Task Get() { + var adds = Enumerable.Range(0, 100) + .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) + .ToList(); + //创建一堆无主键值 - long id = 0; + repos2Song.Insert(adds); - try { + for (var a = 0; a < 10; a++) + adds[a].Title = "dkdkdkdk" + a; - var repos2Song = _orm.GetRepository(); - repos2Song.Where(a => a.Id > 10).ToList(); - //查询结果,进入 states + repos2Song.Update(adds); + //批量修改 - var song = new Song { }; - repos2Song.Insert(song); - id = song.Id; + repos2Song.Delete(adds.Skip(10).Take(20).ToList()); + //批量删除,10-20 元素的主键值会被清除 - var adds = Enumerable.Range(0, 100) - .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) - .ToList(); - //创建一堆无主键值 + adds.Last().Url = "skldfjlksdjglkjjcccc"; + repos2Song.Update(adds.Last()); - repos2Song.Insert(adds); + adds.First().Url = "skldfjlksdjglkjjcccc"; + repos2Song.Update(adds.First()); - for (var a = 0; a < 10; a++) - adds[a].Title = "dkdkdkdk" + a; - repos2Song.Update(adds); - //批量修改 + var ctx = _songContext; + var tag = new Tag + { + Name = "testaddsublist", + Tags = new[] { + new Tag { Name = "sub1" }, + new Tag { Name = "sub2" }, + new Tag { + Name = "sub3", + Tags = new[] { + new Tag { Name = "sub3_01" } + } + } + } + }; + ctx.Tags.Add(tag); - repos2Song.Delete(adds.Skip(10).Take(20).ToList()); - //批量删除,10-20 元素的主键值会被清除 - adds.Last().Url = "skldfjlksdjglkjjcccc"; - repos2Song.Update(adds.Last()); + ctx.UnitOfWork.GetOrBeginTransaction(); - adds.First().Url = "skldfjlksdjglkjjcccc"; - repos2Song.Update(adds.First()); + var tagAsync = new Tag + { + Name = "testaddsublist", + Tags = new[] { + new Tag { Name = "sub1" }, + new Tag { Name = "sub2" }, + new Tag { + Name = "sub3", + Tags = new[] { + new Tag { Name = "sub3_01" } + } + } + } + }; + await ctx.Tags.AddAsync(tagAsync); - var ctx = _songContext; - var tag = new Tag { - Name = "testaddsublist", - Tags = new[] { - new Tag { Name = "sub1" }, - new Tag { Name = "sub2" }, - new Tag { - Name = "sub3", - Tags = new[] { - new Tag { Name = "sub3_01" } - } - } - } - }; - ctx.Tags.Add(tag); + ctx.Songs.Select.Where(a => a.Id > 10).ToList(); + //查询结果,进入 states + song = new Song { }; + //可插入的 song - ctx.UnitOfWork.GetOrBeginTransaction(); + ctx.Songs.Add(song); + id = song.Id; + //因有自增类型,立即开启事务执行SQL,返回自增值 - var tagAsync = new Tag { - Name = "testaddsublist", - Tags = new[] { - new Tag { Name = "sub1" }, - new Tag { Name = "sub2" }, - new Tag { - Name = "sub3", - Tags = new[] { - new Tag { Name = "sub3_01" } - } - } - } - }; - await ctx.Tags.AddAsync(tagAsync); + adds = Enumerable.Range(0, 100) + .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) + .ToList(); + //创建一堆无主键值 + ctx.Songs.AddRange(adds); + //立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行 - ctx.Songs.Select.Where(a => a.Id > 10).ToList(); - //查询结果,进入 states + for (var a = 0; a < 10; a++) + adds[a].Title = "dkdkdkdk" + a; - song = new Song { }; - //可插入的 song + ctx.Songs.UpdateRange(adds); + //批量修改,进入队列 - ctx.Songs.Add(song); - id = song.Id; - //因有自增类型,立即开启事务执行SQL,返回自增值 + ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList()); + //批量删除,进入队列,完成时 10-20 元素的主键值会被清除 - adds = Enumerable.Range(0, 100) - .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) - .ToList(); - //创建一堆无主键值 + //ctx.Songs.Update(adds.First()); - ctx.Songs.AddRange(adds); - //立即执行,将自增值赋给 adds 所有元素,因为有自增类型,如果其他类型,指定传入主键值,不会立即执行 + adds.Last().Url = "skldfjlksdjglkjjcccc"; + ctx.Songs.Update(adds.Last()); - for (var a = 0; a < 10; a++) - adds[a].Title = "dkdkdkdk" + a; + adds.First().Url = "skldfjlksdjglkjjcccc"; + ctx.Songs.Update(adds.First()); - ctx.Songs.UpdateRange(adds); - //批量修改,进入队列 + //单条修改 urls 的值,进入队列 - ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList()); - //批量删除,进入队列,完成时 10-20 元素的主键值会被清除 + //throw new Exception("回滚"); - //ctx.Songs.Update(adds.First()); + //ctx.Songs.Select.First(); + //这里做一个查询,会立即打包【执行队列】,避免没有提交的数据,影响查询结果 - adds.Last().Url = "skldfjlksdjglkjjcccc"; - ctx.Songs.Update(adds.Last()); + ctx.SaveChanges(); + //打包【执行队列】,提交事务 - adds.First().Url = "skldfjlksdjglkjjcccc"; - ctx.Songs.Update(adds.First()); - //单条修改 urls 的值,进入队列 + using (var uow = _orm.CreateUnitOfWork()) + { - //throw new Exception("回滚"); + var reposSong = uow.GetRepository(); + reposSong.Where(a => a.Id > 10).ToList(); + //查询结果,进入 states - //ctx.Songs.Select.First(); - //这里做一个查询,会立即打包【执行队列】,避免没有提交的数据,影响查询结果 + song = new Song { }; + reposSong.Insert(song); + id = song.Id; - ctx.SaveChanges(); - //打包【执行队列】,提交事务 + adds = Enumerable.Range(0, 100) + .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) + .ToList(); + //创建一堆无主键值 + reposSong.Insert(adds); - using (var uow = _orm.CreateUnitOfWork()) { + for (var a = 0; a < 10; a++) + adds[a].Title = "dkdkdkdk" + a; - var reposSong = uow.GetRepository(); - reposSong.Where(a => a.Id > 10).ToList(); - //查询结果,进入 states + reposSong.Update(adds); + //批量修改 - song = new Song { }; - reposSong.Insert(song); - id = song.Id; + reposSong.Delete(adds.Skip(10).Take(20).ToList()); + //批量删除,10-20 元素的主键值会被清除 - adds = Enumerable.Range(0, 100) - .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) - .ToList(); - //创建一堆无主键值 + adds.Last().Url = "skldfjlksdjglkjjcccc"; + reposSong.Update(adds.Last()); - reposSong.Insert(adds); + adds.First().Url = "skldfjlksdjglkjjcccc"; + reposSong.Update(adds.First()); - for (var a = 0; a < 10; a++) - adds[a].Title = "dkdkdkdk" + a; + uow.Commit(); + } - reposSong.Update(adds); - //批量修改 - reposSong.Delete(adds.Skip(10).Take(20).ToList()); - //批量删除,10-20 元素的主键值会被清除 - adds.Last().Url = "skldfjlksdjglkjjcccc"; - reposSong.Update(adds.Last()); + //using (var ctx = new SongContext()) { - adds.First().Url = "skldfjlksdjglkjjcccc"; - reposSong.Update(adds.First()); + // var song = new Song { }; + // await ctx.Songs.AddAsync(song); + // id = song.Id; - uow.Commit(); - } + // var adds = Enumerable.Range(0, 100) + // .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) + // .ToList(); + // await ctx.Songs.AddRangeAsync(adds); + // for (var a = 0; a < adds.Count; a++) + // adds[a].Title = "dkdkdkdk" + a; + // ctx.Songs.UpdateRange(adds); - //using (var ctx = new SongContext()) { + // ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList()); - // var song = new Song { }; - // await ctx.Songs.AddAsync(song); - // id = song.Id; + // //ctx.Songs.Update(adds.First()); - // var adds = Enumerable.Range(0, 100) - // .Select(a => new Song { Create_time = DateTime.Now, Is_deleted = false, Title = "xxxx" + a, Url = "url222" }) - // .ToList(); - // await ctx.Songs.AddRangeAsync(adds); + // adds.Last().Url = "skldfjlksdjglkjjcccc"; + // ctx.Songs.Update(adds.Last()); - // for (var a = 0; a < adds.Count; a++) - // adds[a].Title = "dkdkdkdk" + a; + // //throw new Exception("回滚"); - // ctx.Songs.UpdateRange(adds); + // await ctx.SaveChangesAsync(); + //} + } + catch + { + var item = await _orm.Select().Where(a => a.Id == id).FirstAsync(); - // ctx.Songs.RemoveRange(adds.Skip(10).Take(20).ToList()); + throw; + } - // //ctx.Songs.Update(adds.First()); + var item22 = await _orm.Select().Where(a => a.Id == id).FirstAsync(); + var item33 = await _orm.Select().Where(a => a.Id > id).ToListAsync(); - // adds.Last().Url = "skldfjlksdjglkjjcccc"; - // ctx.Songs.Update(adds.Last()); + return item22.Id.ToString(); + } - // //throw new Exception("回滚"); + // GET api/values/5 + [HttpGet("{id}")] + public ActionResult Get(int id) + { + return "value"; + } - // await ctx.SaveChangesAsync(); - //} - } catch { - var item = await _orm.Select().Where(a => a.Id == id).FirstAsync(); + // POST api/values + [HttpPost] + public void Post([FromBody] string value) + { + } - throw; - } + // PUT api/values/5 + [HttpPut("{id}")] + public void Put(int id, [FromBody] string value) + { + } - var item22 = await _orm.Select().Where(a => a.Id == id).FirstAsync(); - var item33 = await _orm.Select().Where(a => a.Id > id).ToListAsync(); - - return item22.Id.ToString(); - } - - // GET api/values/5 - [HttpGet("{id}")] - public ActionResult Get(int id) { - return "value"; - } - - // POST api/values - [HttpPost] - public void Post([FromBody] string value) { - } - - // PUT api/values/5 - [HttpPut("{id}")] - public void Put(int id, [FromBody] string value) { - } - - // DELETE api/values/5 - [HttpDelete("{id}")] - public void Delete(int id) { - } - } + // DELETE api/values/5 + [HttpDelete("{id}")] + public void Delete(int id) + { + } + } } diff --git a/Examples/dbcontext_01/DbContexts/SongContext.cs b/Examples/dbcontext_01/DbContexts/SongContext.cs index 126c5fd4..2e0ddde9 100644 --- a/Examples/dbcontext_01/DbContexts/SongContext.cs +++ b/Examples/dbcontext_01/DbContexts/SongContext.cs @@ -3,50 +3,55 @@ using FreeSql.DataAnnotations; using System; using System.Collections.Generic; -namespace dbcontext_01 { +namespace dbcontext_01 +{ - public class SongContext : DbContext { + public class SongContext : DbContext + { - public DbSet Songs { get; set; } - public DbSet Tags { get; set; } + public DbSet Songs { get; set; } + public DbSet Tags { get; set; } - //protected override void OnConfiguring(DbContextOptionsBuilder builder) { - // builder.UseFreeSql(dbcontext_01.Startup.Fsql); - //} - } + //protected override void OnConfiguring(DbContextOptionsBuilder builder) { + // builder.UseFreeSql(dbcontext_01.Startup.Fsql); + //} + } - public class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } + public class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } - public virtual ICollection Tags { get; set; } + public virtual ICollection Tags { get; set; } - [Column(IsVersion = true)] - public long versionRow { get; set; } - } - public class Song_tag { - public int Song_id { get; set; } - public virtual Song Song { get; set; } + [Column(IsVersion = true)] + public long versionRow { get; set; } + } + public class Song_tag + { + public int Song_id { get; set; } + public virtual Song Song { get; set; } - public int Tag_id { get; set; } - public virtual Tag Tag { get; set; } - } + public int Tag_id { get; set; } + public virtual Tag Tag { get; set; } + } - public class Tag { - [Column(IsIdentity = true)] - public int Id { get; set; } - public int? Parent_id { get; set; } - public virtual Tag Parent { get; set; } + public class Tag + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public int? Parent_id { get; set; } + public virtual Tag Parent { get; set; } - public decimal? Ddd { get; set; } - public string Name { get; set; } + public decimal? Ddd { get; set; } + public string Name { get; set; } - public virtual ICollection Songs { get; set; } - public virtual ICollection Tags { get; set; } - } + public virtual ICollection Songs { get; set; } + public virtual ICollection Tags { get; set; } + } } diff --git a/Examples/dbcontext_01/Program.cs b/Examples/dbcontext_01/Program.cs index d1a5dafb..ef6e0446 100644 --- a/Examples/dbcontext_01/Program.cs +++ b/Examples/dbcontext_01/Program.cs @@ -17,51 +17,56 @@ namespace dbcontext_01 public class Program { - public class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public string BigNumber { get; set; } + public class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public string BigNumber { get; set; } - [Column(IsVersion = true)]//使用简单 - public long versionRow { get; set; } - } + [Column(IsVersion = true)]//使用简单 + public long versionRow { get; set; } + } - public class SongContext : DbContext { + public class SongContext : DbContext + { - public DbSet Songs { get; set; } + public DbSet Songs { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder builder) { - builder.UseFreeSql(fsql); - } - } - static IFreeSql fsql; - public static void Main(string[] args) { - fsql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\dd2.db;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseLazyLoading(true) - .UseNoneCommandParameter(true) + protected override void OnConfiguring(DbContextOptionsBuilder builder) + { + builder.UseFreeSql(fsql); + } + } + static IFreeSql fsql; + public static void Main(string[] args) + { + fsql = new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\dd2.db;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseLazyLoading(true) + .UseNoneCommandParameter(true) - .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText)) - .Build(); + .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText)) + .Build(); - using (var ctx = new SongContext()) { - var song = new Song { BigNumber = "1000000000000000000" }; - ctx.Songs.Add(song); + using (var ctx = new SongContext()) + { + var song = new Song { BigNumber = "1000000000000000000" }; + ctx.Songs.Add(song); - ctx.Songs.Update(song); + ctx.Songs.Update(song); - song.BigNumber = (BigInteger.Parse(song.BigNumber) + 1).ToString(); - ctx.Songs.Update(song); + song.BigNumber = (BigInteger.Parse(song.BigNumber) + 1).ToString(); + ctx.Songs.Update(song); - ctx.SaveChanges(); + ctx.SaveChanges(); - var sql = fsql.Update().SetSource(song).ToSql(); - } + var sql = fsql.Update().SetSource(song).ToSql(); + } - CreateWebHostBuilder(args).Build().Run(); - } + CreateWebHostBuilder(args).Build().Run(); + } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) diff --git a/Examples/dbcontext_01/Properties/launchSettings.json b/Examples/dbcontext_01/Properties/launchSettings.json index a7caa4d3..b51150e2 100644 --- a/Examples/dbcontext_01/Properties/launchSettings.json +++ b/Examples/dbcontext_01/Properties/launchSettings.json @@ -1,27 +1,27 @@ { - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:53030/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:53030/", + "sslPort": 0 + } }, - "dbcontext_01": { - "commandName": "Project", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:53031/" + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "dbcontext_01": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:53031/" + } } - } } \ No newline at end of file diff --git a/Examples/dbcontext_01/Startup.cs b/Examples/dbcontext_01/Startup.cs index 3955cb87..181e9068 100644 --- a/Examples/dbcontext_01/Startup.cs +++ b/Examples/dbcontext_01/Startup.cs @@ -19,93 +19,101 @@ namespace dbcontext_01 { Configuration = configuration; - Fsql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10") - //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") + Fsql = new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document2.db;Pooling=true;Max Pool Size=10") + //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") - //.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") - //.UseSyncStructureToUpper(true) + //.UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") + //.UseSyncStructureToUpper(true) - .UseAutoSyncStructure(true) - .UseLazyLoading(true) - .UseNoneCommandParameter(true) + .UseAutoSyncStructure(true) + .UseLazyLoading(true) + .UseNoneCommandParameter(true) - .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), - (cmd, log) => Trace.WriteLine(log) - ) - .Build(); - Fsql.Aop.SyncStructureBefore = (s, e) => { - Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName))); - }; - Fsql.Aop.SyncStructureAfter = (s, e) => { - Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)) + " " + e.ElapsedMilliseconds + "ms\r\n" + e.Exception?.Message + e.Sql); - }; + .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), + (cmd, log) => Trace.WriteLine(log) + ) + .Build(); + Fsql.Aop.SyncStructureBefore = (s, e) => + { + Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName))); + }; + Fsql.Aop.SyncStructureAfter = (s, e) => + { + Console.WriteLine(e.Identifier + ": " + string.Join(", ", e.EntityTypes.Select(a => a.FullName)) + " " + e.ElapsedMilliseconds + "ms\r\n" + e.Exception?.Message + e.Sql); + }; - Fsql.Aop.CurdBefore = (s, e) => { - Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + ", " + e.Sql); - }; - Fsql.Aop.CurdAfter = (s, e) => { - Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql); - }; + Fsql.Aop.CurdBefore = (s, e) => + { + Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + ", " + e.Sql); + }; + Fsql.Aop.CurdAfter = (s, e) => + { + Console.WriteLine(e.Identifier + ": " + e.EntityType.FullName + " " + e.ElapsedMilliseconds + "ms, " + e.Sql); + }; - Fsql2 = new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10") - //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseLazyLoading(true) + Fsql2 = new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document222.db;Pooling=true;Max Pool Size=10") + //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseLazyLoading(true) - .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), - (cmd, log) => Trace.WriteLine(log) - ) - .Build(); - } + .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText), + (cmd, log) => Trace.WriteLine(log) + ) + .Build(); + } - enum MySql { } - enum PgSql { } + enum MySql { } + enum PgSql { } - public IConfiguration Configuration { get; } - public static IFreeSql Fsql { get; private set; } - public static IFreeSql Fsql2 { get; private set; } + public IConfiguration Configuration { get; } + public static IFreeSql Fsql { get; private set; } + public static IFreeSql Fsql2 { get; private set; } - public void ConfigureServices(IServiceCollection services) + public void ConfigureServices(IServiceCollection services) { - services.AddMvc(); - services.AddSwaggerGen(options => { - options.SwaggerDoc("v1", new Info { - Version = "v1", - Title = "FreeSql.DbContext API" - }); - //options.IncludeXmlComments(xmlPath); - }); + services.AddMvc(); + services.AddSwaggerGen(options => + { + options.SwaggerDoc("v1", new Info + { + Version = "v1", + Title = "FreeSql.DbContext API" + }); + //options.IncludeXmlComments(xmlPath); + }); - services.AddSingleton(Fsql); - services.AddSingleton>(Fsql2); - services.AddFreeDbContext(options => options.UseFreeSql(Fsql)); + services.AddSingleton(Fsql); + services.AddSingleton>(Fsql2); + services.AddFreeDbContext(options => options.UseFreeSql(Fsql)); - var sql1 = Fsql.Update(1).Set(a => a.Id + 10).ToSql(); - var sql2 = Fsql.Update(1).Set(a => a.Title + 10).ToSql(); - var sql3 = Fsql.Update(1).Set(a => a.Create_time.Value.AddHours(1)).ToSql(); - } + var sql1 = Fsql.Update(1).Set(a => a.Id + 10).ToSql(); + var sql2 = Fsql.Update(1).Set(a => a.Title + 10).ToSql(); + var sql3 = Fsql.Update(1).Set(a => a.Create_time.Value.AddHours(1)).ToSql(); + } - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - Console.OutputEncoding = Encoding.GetEncoding("GB2312"); - Console.InputEncoding = Encoding.GetEncoding("GB2312"); + public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + Console.OutputEncoding = Encoding.GetEncoding("GB2312"); + Console.InputEncoding = Encoding.GetEncoding("GB2312"); - loggerFactory.AddConsole(Configuration.GetSection("Logging")); - loggerFactory.AddDebug(); + loggerFactory.AddConsole(Configuration.GetSection("Logging")); + loggerFactory.AddDebug(); - app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" }); - app.UseDeveloperExceptionPage(); - app.UseMvc(); + app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" }); + app.UseDeveloperExceptionPage(); + app.UseMvc(); - app.UseSwagger(); - app.UseSwaggerUI(c => { - c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1"); - }); - } - } + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1"); + }); + } + } } diff --git a/Examples/dbcontext_01/appsettings.Development.json b/Examples/dbcontext_01/appsettings.Development.json index e203e940..6ba02f3f 100644 --- a/Examples/dbcontext_01/appsettings.Development.json +++ b/Examples/dbcontext_01/appsettings.Development.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } } - } } diff --git a/Examples/dbcontext_01/appsettings.json b/Examples/dbcontext_01/appsettings.json index def9159a..6d451ac2 100644 --- a/Examples/dbcontext_01/appsettings.json +++ b/Examples/dbcontext_01/appsettings.json @@ -1,8 +1,8 @@ { - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" } diff --git a/Examples/efcore_to_freesql/DBContexts/BaseDBContext.cs b/Examples/efcore_to_freesql/DBContexts/BaseDBContext.cs index 98eef7f6..69c4326d 100644 --- a/Examples/efcore_to_freesql/DBContexts/BaseDBContext.cs +++ b/Examples/efcore_to_freesql/DBContexts/BaseDBContext.cs @@ -2,18 +2,22 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; -namespace efcore_to_freesql.DBContexts { +namespace efcore_to_freesql.DBContexts +{ - public class BaseDBContext : DbContext { + public class BaseDBContext : DbContext + { - public static IFreeSql Fsql { get; set; } + public static IFreeSql Fsql { get; set; } - protected override void OnModelCreating(ModelBuilder modelBuilder) { - base.OnModelCreating(modelBuilder); - Fsql.CodeFirst.ConfigEntity(modelBuilder.Model); //ͬ - } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - optionsBuilder.UseSqlite(@"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10"); - } - } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + Fsql.CodeFirst.ConfigEntity(modelBuilder.Model); //ͬ + } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseSqlite(@"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10"); + } + } } \ No newline at end of file diff --git a/Examples/efcore_to_freesql/DBContexts/Topic1Context.cs b/Examples/efcore_to_freesql/DBContexts/Topic1Context.cs index f827c0bc..b0a8d782 100644 --- a/Examples/efcore_to_freesql/DBContexts/Topic1Context.cs +++ b/Examples/efcore_to_freesql/DBContexts/Topic1Context.cs @@ -1,18 +1,21 @@ using efcore_to_freesql.Entitys; using Microsoft.EntityFrameworkCore; -namespace efcore_to_freesql.DBContexts { +namespace efcore_to_freesql.DBContexts +{ - public class Topic1Context : BaseDBContext { + public class Topic1Context : BaseDBContext + { public DbSet Topic1s { get; set; } - protected override void OnModelCreating(ModelBuilder modelBuilder) { + protected override void OnModelCreating(ModelBuilder modelBuilder) + { - modelBuilder.Entity().ToTable("topic1_sss").HasKey(a => a.Id); - modelBuilder.Entity().Property(a => a.Id).HasColumnName("topic1_id").ValueGeneratedOnAdd(); + modelBuilder.Entity().ToTable("topic1_sss").HasKey(a => a.Id); + modelBuilder.Entity().Property(a => a.Id).HasColumnName("topic1_id").ValueGeneratedOnAdd(); - base.OnModelCreating(modelBuilder); - } - } + base.OnModelCreating(modelBuilder); + } + } } \ No newline at end of file diff --git a/Examples/efcore_to_freesql/DBContexts/Topic2Context.cs b/Examples/efcore_to_freesql/DBContexts/Topic2Context.cs index bb978828..0799b0e0 100644 --- a/Examples/efcore_to_freesql/DBContexts/Topic2Context.cs +++ b/Examples/efcore_to_freesql/DBContexts/Topic2Context.cs @@ -1,18 +1,21 @@ using efcore_to_freesql.Entitys; using Microsoft.EntityFrameworkCore; -namespace efcore_to_freesql.DBContexts { +namespace efcore_to_freesql.DBContexts +{ - public class Topic2Context : BaseDBContext { + public class Topic2Context : BaseDBContext + { - public DbSet Topic2s { get; set; } + public DbSet Topic2s { get; set; } - protected override void OnModelCreating(ModelBuilder modelBuilder) { + protected override void OnModelCreating(ModelBuilder modelBuilder) + { - modelBuilder.Entity().ToTable("topic2_sss"); - modelBuilder.Entity().Property(a => a.Id).HasColumnName("topic2_id"); + modelBuilder.Entity().ToTable("topic2_sss"); + modelBuilder.Entity().Property(a => a.Id).HasColumnName("topic2_id"); - base.OnModelCreating(modelBuilder); - } - } + base.OnModelCreating(modelBuilder); + } + } } \ No newline at end of file diff --git a/Examples/efcore_to_freesql/Entitys/Topic1.cs b/Examples/efcore_to_freesql/Entitys/Topic1.cs index cb28c4f4..9bdecef6 100644 --- a/Examples/efcore_to_freesql/Entitys/Topic1.cs +++ b/Examples/efcore_to_freesql/Entitys/Topic1.cs @@ -1,6 +1,7 @@ using System; -namespace efcore_to_freesql.Entitys { +namespace efcore_to_freesql.Entitys +{ public class Topic1 { diff --git a/Examples/efcore_to_freesql/Entitys/Topic2.cs b/Examples/efcore_to_freesql/Entitys/Topic2.cs index 2e503ba4..f0112ba8 100644 --- a/Examples/efcore_to_freesql/Entitys/Topic2.cs +++ b/Examples/efcore_to_freesql/Entitys/Topic2.cs @@ -2,7 +2,8 @@ using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; -namespace efcore_to_freesql.Entitys { +namespace efcore_to_freesql.Entitys +{ public class Topic2 { diff --git a/Examples/efcore_to_freesql/FreeSqlExtensions/CodeFirstExtensions.cs b/Examples/efcore_to_freesql/FreeSqlExtensions/CodeFirstExtensions.cs index 9c480405..1c6d5e68 100644 --- a/Examples/efcore_to_freesql/FreeSqlExtensions/CodeFirstExtensions.cs +++ b/Examples/efcore_to_freesql/FreeSqlExtensions/CodeFirstExtensions.cs @@ -6,60 +6,67 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -public static class CodeFirstExtensions { +public static class CodeFirstExtensions +{ - public static void ConfigEntity(this ICodeFirst codeFirst, IModel efmodel) { + public static void ConfigEntity(this ICodeFirst codeFirst, IModel efmodel) + { - foreach (var type in efmodel.GetEntityTypes()) { + foreach (var type in efmodel.GetEntityTypes()) + { - codeFirst.ConfigEntity(type.ClrType, a => { + codeFirst.ConfigEntity(type.ClrType, a => + { - //表名 - var relationalTableName = type.FindAnnotation("Relational:TableName"); - if (relationalTableName != null) - a.Name(relationalTableName.Value?.ToString() ?? type.ClrType.Name); + //表名 + var relationalTableName = type.FindAnnotation("Relational:TableName"); + if (relationalTableName != null) + a.Name(relationalTableName.Value?.ToString() ?? type.ClrType.Name); - foreach (var prop in type.GetProperties()) { + foreach (var prop in type.GetProperties()) + { - var freeProp = a.Property(prop.Name); + var freeProp = a.Property(prop.Name); - //列名 - var relationalColumnName = prop.FindAnnotation("Relational:ColumnName"); - if (relationalColumnName != null) - freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name); + //列名 + var relationalColumnName = prop.FindAnnotation("Relational:ColumnName"); + if (relationalColumnName != null) + freeProp.Name(relationalColumnName.Value?.ToString() ?? prop.Name); - //主键 - freeProp.IsPrimary(prop.IsPrimaryKey()); + //主键 + freeProp.IsPrimary(prop.IsPrimaryKey()); - //自增 - freeProp.IsIdentity( - prop.ValueGenerated == ValueGenerated.Never || - prop.ValueGenerated == ValueGenerated.OnAdd || - prop.GetAnnotations().Where(z => - z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") //sqlserver 自增 - || z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试 - ).Any() - ); + //自增 + freeProp.IsIdentity( + prop.ValueGenerated == ValueGenerated.Never || + prop.ValueGenerated == ValueGenerated.OnAdd || + prop.GetAnnotations().Where(z => + z.Name == "SqlServer:ValueGenerationStrategy" && z.Value.ToString().Contains("IdentityColumn") //sqlserver 自增 + || z.Value.ToString().Contains("IdentityColumn") //其他数据库实现未经测试 + ).Any() + ); - //可空 - freeProp.IsNullable(prop.AfterSaveBehavior != PropertySaveBehavior.Throw); + //可空 + freeProp.IsNullable(prop.AfterSaveBehavior != PropertySaveBehavior.Throw); - //类型 - var relationalColumnType = prop.FindAnnotation("Relational:ColumnType"); - if (relationalColumnType != null) { + //类型 + var relationalColumnType = prop.FindAnnotation("Relational:ColumnType"); + if (relationalColumnType != null) + { - var dbType = relationalColumnType.ToString(); - if (!string.IsNullOrEmpty(dbType)) { + var dbType = relationalColumnType.ToString(); + if (!string.IsNullOrEmpty(dbType)) + { - var maxLength = prop.FindAnnotation("MaxLength"); - if (maxLength != null) - dbType += $"({maxLength})"; + var maxLength = prop.FindAnnotation("MaxLength"); + if (maxLength != null) + dbType += $"({maxLength})"; - freeProp.DbType(dbType); - } - } - } - }); - } - } + freeProp.DbType(dbType); + } + } + } + }); + } + } } \ No newline at end of file diff --git a/Examples/efcore_to_freesql/Properties/launchSettings.json b/Examples/efcore_to_freesql/Properties/launchSettings.json index 1ff6c056..73df3ed4 100644 --- a/Examples/efcore_to_freesql/Properties/launchSettings.json +++ b/Examples/efcore_to_freesql/Properties/launchSettings.json @@ -1,30 +1,30 @@ { - "$schema": "http://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:58143", - "sslPort": 44349 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "api/values", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:58143", + "sslPort": 44349 + } }, - "efcore_to_freesql": { - "commandName": "Project", - "launchBrowser": true, - "launchUrl": "api/values", - "applicationUrl": "https://localhost:5001;http://localhost:5000", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "api/values", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "efcore_to_freesql": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "api/values", + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } } - } } \ No newline at end of file diff --git a/Examples/efcore_to_freesql/Startup.cs b/Examples/efcore_to_freesql/Startup.cs index 8f30257d..0e9eea21 100644 --- a/Examples/efcore_to_freesql/Startup.cs +++ b/Examples/efcore_to_freesql/Startup.cs @@ -22,57 +22,59 @@ namespace efcore_to_freesql { Configuration = configuration; - Fsql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .Build(); + Fsql = new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .Build(); - DBContexts.BaseDBContext.Fsql = Fsql; + DBContexts.BaseDBContext.Fsql = Fsql; - var sql11 = Fsql.Select().ToSql(); - //SELECT a."Id", a."Title", a."CreateTime" FROM "Topic1" a - var sql12 = Fsql.Insert().AppendData(new Topic1()).ToSql(); - //INSERT INTO "Topic1"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0) + var sql11 = Fsql.Select().ToSql(); + //SELECT a."Id", a."Title", a."CreateTime" FROM "Topic1" a + var sql12 = Fsql.Insert().AppendData(new Topic1()).ToSql(); + //INSERT INTO "Topic1"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0) - var sql21 = Fsql.Select().ToSql(); - //SELECT a."Id", a."Title", a."CreateTime" FROM "Topic2" a - var sql22 = Fsql.Insert().AppendData(new Topic2()).ToSql(); - //INSERT INTO "Topic2"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0) + var sql21 = Fsql.Select().ToSql(); + //SELECT a."Id", a."Title", a."CreateTime" FROM "Topic2" a + var sql22 = Fsql.Insert().AppendData(new Topic2()).ToSql(); + //INSERT INTO "Topic2"("Id", "Title", "CreateTime") VALUES(@Id0, @Title0, @CreateTime0) - using (var db = new Topic1Context()) { - db.Topic1s.Add(new Topic1()); - } - using (var db = new Topic2Context()) { - db.Topic2s.Add(new Topic2()); - } + using (var db = new Topic1Context()) + { + db.Topic1s.Add(new Topic1()); + } + using (var db = new Topic2Context()) + { + db.Topic2s.Add(new Topic2()); + } - var sql13 = Fsql.Select().ToSql(); - //SELECT a."topic1_id", a."Title", a."CreateTime" FROM "topic1_sss" a - var sql14 = Fsql.Insert().AppendData(new Topic1()).ToSql(); - //INSERT INTO "topic1_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0) + var sql13 = Fsql.Select().ToSql(); + //SELECT a."topic1_id", a."Title", a."CreateTime" FROM "topic1_sss" a + var sql14 = Fsql.Insert().AppendData(new Topic1()).ToSql(); + //INSERT INTO "topic1_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0) - var sql23 = Fsql.Select().ToSql(); - //SELECT a."topic2_id", a."Title", a."CreateTime" FROM "topic2_sss" a - var sql24 = Fsql.Insert().AppendData(new Topic2()).ToSql(); - //INSERT INTO "topic2_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0) - } + var sql23 = Fsql.Select().ToSql(); + //SELECT a."topic2_id", a."Title", a."CreateTime" FROM "topic2_sss" a + var sql24 = Fsql.Insert().AppendData(new Topic2()).ToSql(); + //INSERT INTO "topic2_sss"("Title", "CreateTime") VALUES(@Title0, @CreateTime0) + } - public IConfiguration Configuration { get; } - public IFreeSql Fsql { get; } + public IConfiguration Configuration { get; } + public IFreeSql Fsql { get; } - public void ConfigureServices(IServiceCollection services) + public void ConfigureServices(IServiceCollection services) { - services.AddSingleton(Fsql); - services.AddMvc(); + services.AddSingleton(Fsql); + services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - loggerFactory.AddConsole(Configuration.GetSection("Logging")); - loggerFactory.AddDebug(); + loggerFactory.AddConsole(Configuration.GetSection("Logging")); + loggerFactory.AddDebug(); - app.UseDeveloperExceptionPage(); - app.UseMvc(); - } + app.UseDeveloperExceptionPage(); + app.UseMvc(); + } } } diff --git a/Examples/efcore_to_freesql/appsettings.Development.json b/Examples/efcore_to_freesql/appsettings.Development.json index e203e940..6ba02f3f 100644 --- a/Examples/efcore_to_freesql/appsettings.Development.json +++ b/Examples/efcore_to_freesql/appsettings.Development.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } } - } } diff --git a/Examples/efcore_to_freesql/appsettings.json b/Examples/efcore_to_freesql/appsettings.json index def9159a..6d451ac2 100644 --- a/Examples/efcore_to_freesql/appsettings.json +++ b/Examples/efcore_to_freesql/appsettings.json @@ -1,8 +1,8 @@ { - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" } diff --git a/Examples/orm_vs/Program.cs b/Examples/orm_vs/Program.cs index e90b1aaf..729b9c36 100644 --- a/Examples/orm_vs/Program.cs +++ b/Examples/orm_vs/Program.cs @@ -14,288 +14,317 @@ namespace orm_vs { class Program { - static IFreeSql fsql = new FreeSql.FreeSqlBuilder() - //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20") - .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=20") - .UseAutoSyncStructure(false) - .UseNoneCommandParameter(true) - //.UseConfigEntityFromDbFirst(true) - .Build(); + static IFreeSql fsql = new FreeSql.FreeSqlBuilder() + //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=20") + .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=20") + .UseAutoSyncStructure(false) + .UseNoneCommandParameter(true) + //.UseConfigEntityFromDbFirst(true) + .Build(); - static SqlSugarClient sugar { - get => new SqlSugarClient(new ConnectionConfig() { - //不欺负,让连接池100个最小 - //ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20", - //DbType = DbType.SqlServer, - ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20", - DbType = DbType.MySql, - IsAutoCloseConnection = true, - InitKeyType = InitKeyType.Attribute - }); - } + static SqlSugarClient sugar + { + get => new SqlSugarClient(new ConnectionConfig() + { + //不欺负,让连接池100个最小 + //ConnectionString = "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=20;Max Pool Size=20", + //DbType = DbType.SqlServer, + ConnectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=20;Max Pool Size=20", + DbType = DbType.MySql, + IsAutoCloseConnection = true, + InitKeyType = InitKeyType.Attribute + }); + } - class SongContext : DbContext { - public DbSet Songs { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { - //optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21"); - optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21"); - } - } + class SongContext : DbContext + { + public DbSet Songs { get; set; } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + //optionsBuilder.UseSqlServer(@"Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Min Pool Size=21;Max Pool Size=21"); + optionsBuilder.UseMySql("Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Min Pool Size=21;Max Pool Size=21"); + } + } - static void Main(string[] args) { + static void Main(string[] args) + { - fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag)); - //sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag)); - //sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements + fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag)); + //sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag)); + //sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements - sugar.Aop.OnLogExecuted = (s, e) => { - Trace.WriteLine(s); - }; - //测试前清空数据 - fsql.Delete().Where(a => a.Id > 0).ExecuteAffrows(); - sugar.Deleteable().Where(a => a.Id > 0).ExecuteCommand(); - fsql.Ado.ExecuteNonQuery("delete from efcore_song"); + sugar.Aop.OnLogExecuted = (s, e) => + { + Trace.WriteLine(s); + }; + //测试前清空数据 + fsql.Delete().Where(a => a.Id > 0).ExecuteAffrows(); + sugar.Deleteable().Where(a => a.Id > 0).ExecuteCommand(); + fsql.Ado.ExecuteNonQuery("delete from efcore_song"); - var sb = new StringBuilder(); - Console.WriteLine("插入性能:"); - Insert(sb, 1000, 1); - Console.Write(sb.ToString()); - sb.Clear(); - Insert(sb, 1000, 10); - Console.Write(sb.ToString()); - sb.Clear(); + var sb = new StringBuilder(); + Console.WriteLine("插入性能:"); + Insert(sb, 1000, 1); + Console.Write(sb.ToString()); + sb.Clear(); + Insert(sb, 1000, 10); + Console.Write(sb.ToString()); + sb.Clear(); - Insert(sb, 1, 1000); - Console.Write(sb.ToString()); - sb.Clear(); - Insert(sb, 1, 10000); - Console.Write(sb.ToString()); - sb.Clear(); - Insert(sb, 1, 50000); - Console.Write(sb.ToString()); - sb.Clear(); - Insert(sb, 1, 100000); - Console.Write(sb.ToString()); - sb.Clear(); + Insert(sb, 1, 1000); + Console.Write(sb.ToString()); + sb.Clear(); + Insert(sb, 1, 10000); + Console.Write(sb.ToString()); + sb.Clear(); + Insert(sb, 1, 50000); + Console.Write(sb.ToString()); + sb.Clear(); + Insert(sb, 1, 100000); + Console.Write(sb.ToString()); + sb.Clear(); - Console.WriteLine("查询性能:"); - Select(sb, 1000, 1); - Console.Write(sb.ToString()); - sb.Clear(); - Select(sb, 1000, 10); - Console.Write(sb.ToString()); - sb.Clear(); + Console.WriteLine("查询性能:"); + Select(sb, 1000, 1); + Console.Write(sb.ToString()); + sb.Clear(); + Select(sb, 1000, 10); + Console.Write(sb.ToString()); + sb.Clear(); - Select(sb, 1, 1000); - Console.Write(sb.ToString()); - sb.Clear(); - Select(sb, 1, 10000); - Console.Write(sb.ToString()); - sb.Clear(); - Select(sb, 1, 50000); - Console.Write(sb.ToString()); - sb.Clear(); - Select(sb, 1, 100000); - Console.Write(sb.ToString()); - sb.Clear(); + Select(sb, 1, 1000); + Console.Write(sb.ToString()); + sb.Clear(); + Select(sb, 1, 10000); + Console.Write(sb.ToString()); + sb.Clear(); + Select(sb, 1, 50000); + Console.Write(sb.ToString()); + sb.Clear(); + Select(sb, 1, 100000); + Console.Write(sb.ToString()); + sb.Clear(); - Console.WriteLine("更新:"); - Update(sb, 1000, 1); - Console.Write(sb.ToString()); - sb.Clear(); - Update(sb, 1000, 10); - Console.Write(sb.ToString()); - sb.Clear(); + Console.WriteLine("更新:"); + Update(sb, 1000, 1); + Console.Write(sb.ToString()); + sb.Clear(); + Update(sb, 1000, 10); + Console.Write(sb.ToString()); + sb.Clear(); - Update(sb, 1, 1000); - Console.Write(sb.ToString()); - sb.Clear(); - Update(sb, 1, 10000); - Console.Write(sb.ToString()); - sb.Clear(); - Update(sb, 1, 50000); - Console.Write(sb.ToString()); - sb.Clear(); - Update(sb, 1, 100000); - Console.Write(sb.ToString()); - sb.Clear(); + Update(sb, 1, 1000); + Console.Write(sb.ToString()); + sb.Clear(); + Update(sb, 1, 10000); + Console.Write(sb.ToString()); + sb.Clear(); + Update(sb, 1, 50000); + Console.Write(sb.ToString()); + sb.Clear(); + Update(sb, 1, 100000); + Console.Write(sb.ToString()); + sb.Clear(); - Console.WriteLine("测试结束,按任意键退出..."); - Console.ReadKey(); - } + Console.WriteLine("测试结束,按任意键退出..."); + Console.ReadKey(); + } - static void Select(StringBuilder sb, int forTime, int size) { - Stopwatch sw = new Stopwatch(); - sw.Restart(); - for (var a = 0; a < forTime; a++) - fsql.Select().Limit(size).ToList(); - sw.Stop(); - sb.AppendLine($"FreeSql Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms"); + static void Select(StringBuilder sb, int forTime, int size) + { + Stopwatch sw = new Stopwatch(); + sw.Restart(); + for (var a = 0; a < forTime; a++) + fsql.Select().Limit(size).ToList(); + sw.Stop(); + sb.AppendLine($"FreeSql Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms"); - sw.Restart(); - for (var a = 0; a < forTime; a++) - sugar.Queryable().Take(size).ToList(); - sw.Stop(); - sb.AppendLine($"SqlSugar Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms"); + sw.Restart(); + for (var a = 0; a < forTime; a++) + sugar.Queryable().Take(size).ToList(); + sw.Stop(); + sb.AppendLine($"SqlSugar Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms"); - sw.Restart(); - for (var a = 0; a < forTime; a++) { - using (var db = new SongContext()) { - db.Songs.Take(size).AsNoTracking().ToList(); - } - } - sw.Stop(); - sb.AppendLine($"EFCore Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n"); - } + sw.Restart(); + for (var a = 0; a < forTime; a++) + { + using (var db = new SongContext()) + { + db.Songs.Take(size).AsNoTracking().ToList(); + } + } + sw.Stop(); + sb.AppendLine($"EFCore Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n"); + } - static void Insert(StringBuilder sb, int forTime, int size) { - var songs = Enumerable.Range(0, size).Select(a => new Song { - Create_time = DateTime.Now, - Is_deleted = false, - Title = $"Insert_{a}", - Url = $"Url_{a}" - }); + static void Insert(StringBuilder sb, int forTime, int size) + { + var songs = Enumerable.Range(0, size).Select(a => new Song + { + Create_time = DateTime.Now, + Is_deleted = false, + Title = $"Insert_{a}", + Url = $"Url_{a}" + }); - //预热 - fsql.Insert(songs.First()).ExecuteAffrows(); - sugar.Insertable(songs.First()).ExecuteCommand(); - using (var db = new SongContext()) { - //db.Configuration.AutoDetectChangesEnabled = false; - db.Songs.AddRange(songs.First()); - db.SaveChanges(); - } - Stopwatch sw = new Stopwatch(); + //预热 + fsql.Insert(songs.First()).ExecuteAffrows(); + sugar.Insertable(songs.First()).ExecuteCommand(); + using (var db = new SongContext()) + { + //db.Configuration.AutoDetectChangesEnabled = false; + db.Songs.AddRange(songs.First()); + db.SaveChanges(); + } + Stopwatch sw = new Stopwatch(); - sw.Restart(); - for (var a = 0; a < forTime; a++) { - fsql.Insert(songs).ExecuteAffrows(); - //using (var db = new FreeSongContext()) { - // //db.Configuration.AutoDetectChangesEnabled = false; - // db.Songs.AddRange(songs.ToArray()); - // db.SaveChanges(); - //} - } - sw.Stop(); - sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms"); + sw.Restart(); + for (var a = 0; a < forTime; a++) + { + fsql.Insert(songs).ExecuteAffrows(); + //using (var db = new FreeSongContext()) { + // //db.Configuration.AutoDetectChangesEnabled = false; + // db.Songs.AddRange(songs.ToArray()); + // db.SaveChanges(); + //} + } + sw.Stop(); + sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms"); - sw.Restart(); - Exception sugarEx = null; - try { - for (var a = 0; a < forTime; a++) - sugar.Insertable(songs.ToArray()).ExecuteCommand(); - } catch (Exception ex) { - sugarEx = ex; - } - sw.Stop(); - sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : "")); + sw.Restart(); + Exception sugarEx = null; + try + { + for (var a = 0; a < forTime; a++) + sugar.Insertable(songs.ToArray()).ExecuteCommand(); + } + catch (Exception ex) + { + sugarEx = ex; + } + sw.Stop(); + sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : "")); - sw.Restart(); - for (var a = 0; a < forTime; a++) { + sw.Restart(); + for (var a = 0; a < forTime; a++) + { - using (var db = new SongContext()) { - //db.Configuration.AutoDetectChangesEnabled = false; - db.Songs.AddRange(songs.ToArray()); - db.SaveChanges(); - } - } - sw.Stop(); - sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n"); - } + using (var db = new SongContext()) + { + //db.Configuration.AutoDetectChangesEnabled = false; + db.Songs.AddRange(songs.ToArray()); + db.SaveChanges(); + } + } + sw.Stop(); + sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n"); + } - static void Update(StringBuilder sb, int forTime, int size) { - Stopwatch sw = new Stopwatch(); + static void Update(StringBuilder sb, int forTime, int size) + { + Stopwatch sw = new Stopwatch(); - var songs = fsql.Select().Limit(size).ToList(); - sw.Restart(); - for (var a = 0; a < forTime; a++) { - fsql.Update().SetSource(songs).ExecuteAffrows(); - } - sw.Stop(); - sb.AppendLine($"FreeSql Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms"); + var songs = fsql.Select().Limit(size).ToList(); + sw.Restart(); + for (var a = 0; a < forTime; a++) + { + fsql.Update().SetSource(songs).ExecuteAffrows(); + } + sw.Stop(); + sb.AppendLine($"FreeSql Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms"); - songs = sugar.Queryable().Take(size).ToList(); - sw.Restart(); - Exception sugarEx = null; - try { - for (var a = 0; a < forTime; a++) - sugar.Updateable(songs).ExecuteCommand(); - } catch (Exception ex) { - sugarEx = ex; - } - sw.Stop(); - sb.AppendLine($"SqlSugar Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : "")); + songs = sugar.Queryable().Take(size).ToList(); + sw.Restart(); + Exception sugarEx = null; + try + { + for (var a = 0; a < forTime; a++) + sugar.Updateable(songs).ExecuteCommand(); + } + catch (Exception ex) + { + sugarEx = ex; + } + sw.Stop(); + sb.AppendLine($"SqlSugar Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : "")); - using (var db = new SongContext()) { - songs = db.Songs.Take(size).AsNoTracking().ToList(); - } - sw.Restart(); - for (var a = 0; a < forTime; a++) { + using (var db = new SongContext()) + { + songs = db.Songs.Take(size).AsNoTracking().ToList(); + } + sw.Restart(); + for (var a = 0; a < forTime; a++) + { - using (var db = new SongContext()) { - //db.Configuration.AutoDetectChangesEnabled = false; - db.Songs.UpdateRange(songs.ToArray()); - db.SaveChanges(); - } - } - sw.Stop(); - sb.AppendLine($"EFCore Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n"); - } - } + using (var db = new SongContext()) + { + //db.Configuration.AutoDetectChangesEnabled = false; + db.Songs.UpdateRange(songs.ToArray()); + db.SaveChanges(); + } + } + sw.Stop(); + sb.AppendLine($"EFCore Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n"); + } + } - [FreeSql.DataAnnotations.Table(Name = "freesql_song")] - [SugarTable("sugar_song")] - [Table("efcore_song")] - public class Song { - [FreeSql.DataAnnotations.Column(IsIdentity = true)] - [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] - [Key] - [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } + [FreeSql.DataAnnotations.Table(Name = "freesql_song")] + [SugarTable("sugar_song")] + [Table("efcore_song")] + public class Song + { + [FreeSql.DataAnnotations.Column(IsIdentity = true)] + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } - [SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual ICollection Tags { get; set; } - } - [FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")] - [SugarTable("sugar_song_tag")] - [Table("efcore_song_tag")] - public class Song_tag { - public int Song_id { get; set; } - [SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual Song Song { get; set; } + [SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual ICollection Tags { get; set; } + } + [FreeSql.DataAnnotations.Table(Name = "freesql_song_tag")] + [SugarTable("sugar_song_tag")] + [Table("efcore_song_tag")] + public class Song_tag + { + public int Song_id { get; set; } + [SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual Song Song { get; set; } - public int Tag_id { get; set; } - [SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual Tag Tag { get; set; } - } - [FreeSql.DataAnnotations.Table(Name = "freesql_tag")] - [SugarTable("sugar_tag")] - [Table("efcore_tag")] - public class Tag { - [FreeSql.DataAnnotations.Column(IsIdentity = true)] - [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] - [Key] - [DatabaseGenerated(DatabaseGeneratedOption.Identity)] - public int Id { get; set; } - public int? Parent_id { get; set; } - [SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual Tag Parent { get; set; } + public int Tag_id { get; set; } + [SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual Tag Tag { get; set; } + } + [FreeSql.DataAnnotations.Table(Name = "freesql_tag")] + [SugarTable("sugar_tag")] + [Table("efcore_tag")] + public class Tag + { + [FreeSql.DataAnnotations.Column(IsIdentity = true)] + [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + public int? Parent_id { get; set; } + [SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual Tag Parent { get; set; } - public decimal? Ddd { get; set; } - public string Name { get; set; } + public decimal? Ddd { get; set; } + public string Name { get; set; } - [SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual ICollection Songs { get; set; } - [SugarColumn(IsIgnore = true)] - [NotMapped] - public virtual ICollection Tags { get; set; } - } + [SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual ICollection Songs { get; set; } + [SugarColumn(IsIgnore = true)] + [NotMapped] + public virtual ICollection Tags { get; set; } + } } diff --git a/Examples/repository_01/Controllers/SongController.cs b/Examples/repository_01/Controllers/SongController.cs index d162c33c..51d9b9c8 100644 --- a/Examples/repository_01/Controllers/SongController.cs +++ b/Examples/repository_01/Controllers/SongController.cs @@ -6,93 +6,107 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace restful.Controllers { +namespace restful.Controllers +{ - public class SongRepository : GuidRepository { - public SongRepository(IFreeSql fsql) : base(fsql) { - } - } + public class SongRepository : GuidRepository + { + public SongRepository(IFreeSql fsql) : base(fsql) + { + } + } - [Route("restapi/[controller]")] - public class SongsController : Controller { + [Route("restapi/[controller]")] + public class SongsController : Controller + { - BaseRepository _songRepository; + BaseRepository _songRepository; - public class xxxx { - public int Id { get; set; } + public class xxxx + { + public int Id { get; set; } - public bool IsDeleted { get; set; } - } + public bool IsDeleted { get; set; } + } - - public SongsController(IFreeSql fsql, - GuidRepository repos1, - GuidRepository repos2, - DefaultRepository repos11, - DefaultRepository repos21, + public SongsController(IFreeSql fsql, + GuidRepository repos1, + GuidRepository repos2, - BaseRepository repos3, BaseRepository repos4, - IBasicRepository repos31, IBasicRepository repos41, - IReadOnlyRepository repos311, IReadOnlyRepository repos411, + DefaultRepository repos11, + DefaultRepository repos21, - SongRepository reposSong - ) { - _songRepository = repos4; + BaseRepository repos3, BaseRepository repos4, + IBasicRepository repos31, IBasicRepository repos41, + IReadOnlyRepository repos311, IReadOnlyRepository repos411, - //test code - var curd1 = fsql.GetRepository(); - var curd2 = fsql.GetRepository(); - var curd3 = fsql.GetRepository(); - var curd4 = fsql.GetGuidRepository(); + SongRepository reposSong + ) + { + _songRepository = repos4; - Console.WriteLine(repos1.Select.ToSql()); - Console.WriteLine(reposSong.Select.ToSql()); + //test code + var curd1 = fsql.GetRepository(); + var curd2 = fsql.GetRepository(); + var curd3 = fsql.GetRepository(); + var curd4 = fsql.GetGuidRepository(); - Console.WriteLine(repos2.Select.ToSql()); - Console.WriteLine(repos21.Select.ToSql()); + Console.WriteLine(repos1.Select.ToSql()); + Console.WriteLine(reposSong.Select.ToSql()); - using (reposSong.DataFilter.DisableAll()) { - Console.WriteLine(reposSong.Select.ToSql()); - } - } + Console.WriteLine(repos2.Select.ToSql()); + Console.WriteLine(repos21.Select.ToSql()); - [HttpGet] - public Task> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20) { - return _songRepository.Select.WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync(); - } + using (reposSong.DataFilter.DisableAll()) + { + Console.WriteLine(reposSong.Select.ToSql()); + } + } - [HttpGet("{id}")] - public Task GetItem([FromRoute] int id) { - return _songRepository.FindAsync(id); - } + [HttpGet] + public Task> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20) + { + return _songRepository.Select.WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync(); + } - public class ModelSong { - public string title { get; set; } - } + [HttpGet("{id}")] + public Task GetItem([FromRoute] int id) + { + return _songRepository.FindAsync(id); + } - [HttpPost, ProducesResponseType(201)] - public Task Create([FromBody] ModelSong model) { - return _songRepository.InsertAsync(new Song { Title = model.title }); - } + public class ModelSong + { + public string title { get; set; } + } - [HttpPut("{id}")] - public Task Update([FromRoute] int id, [FromBody] ModelSong model) { - return _songRepository.UpdateAsync(new Song { Id = id, Title = model.title }); - } + [HttpPost, ProducesResponseType(201)] + public Task Create([FromBody] ModelSong model) + { + return _songRepository.InsertAsync(new Song { Title = model.title }); + } - [HttpPatch("{id}")] - async public Task UpdateDiy([FromRoute] int id, [FromForm] string title) { - var up = _songRepository.UpdateDiy.Where(a => a.Id == id); - if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title); - var ret = await up.ExecuteUpdatedAsync(); - return ret.FirstOrDefault(); - } + [HttpPut("{id}")] + public Task Update([FromRoute] int id, [FromBody] ModelSong model) + { + return _songRepository.UpdateAsync(new Song { Id = id, Title = model.title }); + } - [HttpDelete("{id}"), ProducesResponseType(204)] - public Task Delete([FromRoute] int id) { - return _songRepository.DeleteAsync(a => a.Id == id); - } - } + [HttpPatch("{id}")] + async public Task UpdateDiy([FromRoute] int id, [FromForm] string title) + { + var up = _songRepository.UpdateDiy.Where(a => a.Id == id); + if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title); + var ret = await up.ExecuteUpdatedAsync(); + return ret.FirstOrDefault(); + } + + [HttpDelete("{id}"), ProducesResponseType(204)] + public Task Delete([FromRoute] int id) + { + return _songRepository.DeleteAsync(a => a.Id == id); + } + } } diff --git a/Examples/repository_01/Entitys/Song.cs b/Examples/repository_01/Entitys/Song.cs index 8c8a8a14..0ac4f16a 100644 --- a/Examples/repository_01/Entitys/Song.cs +++ b/Examples/repository_01/Entitys/Song.cs @@ -1,11 +1,13 @@ using FreeSql.DataAnnotations; using repository_01; -namespace restful.Entitys { - public class Song { +namespace restful.Entitys +{ + public class Song + { - [Column(IsIdentity = true)] - public int Id { get; set; } - public string Title { get; set; } - } + [Column(IsIdentity = true)] + public int Id { get; set; } + public string Title { get; set; } + } } diff --git a/Examples/repository_01/Properties/launchSettings.json b/Examples/repository_01/Properties/launchSettings.json index 0426ce6f..e58a6fc7 100644 --- a/Examples/repository_01/Properties/launchSettings.json +++ b/Examples/repository_01/Properties/launchSettings.json @@ -1,27 +1,27 @@ { - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:52751/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:52751/", + "sslPort": 0 + } }, - "repository_01": { - "commandName": "Project", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:52752/" + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "repository_01": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:52752/" + } } - } } \ No newline at end of file diff --git a/Examples/repository_01/Startup.cs b/Examples/repository_01/Startup.cs index 07243127..24b5b025 100644 --- a/Examples/repository_01/Startup.cs +++ b/Examples/repository_01/Startup.cs @@ -13,86 +13,98 @@ using System.Diagnostics; using System.Linq; using System.Text; -namespace repository_01 { +namespace repository_01 +{ - /// - /// 用户密码信息 - /// - public class Sys1UserLogOn { - [Column(IsPrimary = true, Name = "Id")] - public Guid UserLogOnId { get; set; } - public virtual Sys1User User { get; set; } - } - public class Sys1User { - [Column(IsPrimary = true, Name = "Id")] - public Guid UserId { get; set; } - public virtual Sys1UserLogOn UserLogOn { get; set; } - } - - public class Startup { - public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { - Configuration = configuration; + /// + /// 用户密码信息 + /// + public class Sys1UserLogOn + { + [Column(IsPrimary = true, Name = "Id")] + public Guid UserLogOnId { get; set; } + public virtual Sys1User User { get; set; } + } + public class Sys1User + { + [Column(IsPrimary = true, Name = "Id")] + public Guid UserId { get; set; } + public virtual Sys1UserLogOn UserLogOn { get; set; } + } - Fsql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseLazyLoading(true) + public class Startup + { + public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) + { + Configuration = configuration; - .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText)) - .Build(); + Fsql = new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseLazyLoading(true) - var sysu = new Sys1User { }; - Fsql.Insert().AppendData(sysu).ExecuteAffrows(); - Fsql.Insert().AppendData(new Sys1UserLogOn { UserLogOnId = sysu.UserId }).ExecuteAffrows(); - var a = Fsql.Select().ToList(); - var b = Fsql.Select().Any(); - } + .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText)) + .Build(); - public IConfiguration Configuration { get; } - public static IFreeSql Fsql { get; private set; } + var sysu = new Sys1User { }; + Fsql.Insert().AppendData(sysu).ExecuteAffrows(); + Fsql.Insert().AppendData(new Sys1UserLogOn { UserLogOnId = sysu.UserId }).ExecuteAffrows(); + var a = Fsql.Select().ToList(); + var b = Fsql.Select().Any(); + } - public void ConfigureServices(IServiceCollection services) { + public IConfiguration Configuration { get; } + public static IFreeSql Fsql { get; private set; } - //services.AddTransient(s => s.) + public void ConfigureServices(IServiceCollection services) + { - services.AddMvc(); - services.AddSwaggerGen(options => { - options.SwaggerDoc("v1", new Info { - Version = "v1", - Title = "FreeSql.RESTful API" - }); - //options.IncludeXmlComments(xmlPath); - }); + //services.AddTransient(s => s.) - services.AddSingleton(Fsql); + services.AddMvc(); + services.AddSwaggerGen(options => + { + options.SwaggerDoc("v1", new Info + { + Version = "v1", + Title = "FreeSql.RESTful API" + }); + //options.IncludeXmlComments(xmlPath); + }); - services.AddFreeRepository(filter => { - filter - //.Apply("test", a => a.Title == DateTime.Now.ToString() + System.Threading.Thread.CurrentThread.ManagedThreadId) - .Apply("softdelete", a => a.IsDeleted == false); - }, this.GetType().Assembly); - } + services.AddSingleton(Fsql); - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - Console.OutputEncoding = Encoding.GetEncoding("GB2312"); - Console.InputEncoding = Encoding.GetEncoding("GB2312"); + services.AddFreeRepository(filter => + { + filter + //.Apply("test", a => a.Title == DateTime.Now.ToString() + System.Threading.Thread.CurrentThread.ManagedThreadId) + .Apply("softdelete", a => a.IsDeleted == false); + }, this.GetType().Assembly); + } - loggerFactory.AddConsole(Configuration.GetSection("Logging")); - loggerFactory.AddDebug(); + public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + Console.OutputEncoding = Encoding.GetEncoding("GB2312"); + Console.InputEncoding = Encoding.GetEncoding("GB2312"); - app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" }); - app.UseDeveloperExceptionPage(); - app.UseMvc(); + loggerFactory.AddConsole(Configuration.GetSection("Logging")); + loggerFactory.AddDebug(); - app.UseSwagger(); - app.UseSwaggerUI(c => { - c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1"); - }); - } - } + app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" }); + app.UseDeveloperExceptionPage(); + app.UseMvc(); - public interface ISoftDelete { - bool IsDeleted { get; set; } - } + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1"); + }); + } + } + + public interface ISoftDelete + { + bool IsDeleted { get; set; } + } } diff --git a/Examples/repository_01/appsettings.Development.json b/Examples/repository_01/appsettings.Development.json index 86f6b8f7..2d586cdf 100644 --- a/Examples/repository_01/appsettings.Development.json +++ b/Examples/repository_01/appsettings.Development.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Warning", - "Microsoft": "Warning" - } - } + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Warning", + "Microsoft": "Warning" + } + } } diff --git a/Examples/repository_01/appsettings.json b/Examples/repository_01/appsettings.json index def9159a..6d451ac2 100644 --- a/Examples/repository_01/appsettings.json +++ b/Examples/repository_01/appsettings.json @@ -1,8 +1,8 @@ { - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" } diff --git a/Examples/restful/Controllers/SongController.cs b/Examples/restful/Controllers/SongController.cs index 8954e800..0cd631ae 100644 --- a/Examples/restful/Controllers/SongController.cs +++ b/Examples/restful/Controllers/SongController.cs @@ -4,56 +4,66 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace restful.Controllers { +namespace restful.Controllers +{ - [Route("restapi/[controller]")] - public class SongsController : Controller { + [Route("restapi/[controller]")] + public class SongsController : Controller + { - IFreeSql _fsql; + IFreeSql _fsql; - public SongsController(IFreeSql fsql) { - _fsql = fsql; - } + public SongsController(IFreeSql fsql) + { + _fsql = fsql; + } - [HttpGet] - public Task> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20) { - return _fsql.Select().WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync(); - } + [HttpGet] + public Task> GetItems([FromQuery] string key, [FromQuery] int page = 1, [FromQuery] int limit = 20) + { + return _fsql.Select().WhereIf(!string.IsNullOrEmpty(key), a => a.Title.Contains(key)).Page(page, limit).ToListAsync(); + } - [HttpGet("{id}")] - public Task GetItem([FromRoute] int id) { - return _fsql.Select().Where(a => a.Id == id).ToOneAsync(); - } + [HttpGet("{id}")] + public Task GetItem([FromRoute] int id) + { + return _fsql.Select().Where(a => a.Id == id).ToOneAsync(); + } - public class ModelSong { - public string title { get; set; } - } + public class ModelSong + { + public string title { get; set; } + } - [HttpPost, ProducesResponseType(201)] - async public Task Create([FromBody] ModelSong model) { - var ret = await _fsql.Insert().AppendData(new Song { Title = model.title }).ExecuteInsertedAsync(); - return ret.FirstOrDefault(); - } + [HttpPost, ProducesResponseType(201)] + async public Task Create([FromBody] ModelSong model) + { + var ret = await _fsql.Insert().AppendData(new Song { Title = model.title }).ExecuteInsertedAsync(); + return ret.FirstOrDefault(); + } - [HttpPut("{id}")] - async public Task Update([FromRoute] int id, [FromBody] ModelSong model) { - var ret = await _fsql.Update().SetSource(new Song { Id = id, Title = model.title }).ExecuteUpdatedAsync(); - return ret.FirstOrDefault(); - } + [HttpPut("{id}")] + async public Task Update([FromRoute] int id, [FromBody] ModelSong model) + { + var ret = await _fsql.Update().SetSource(new Song { Id = id, Title = model.title }).ExecuteUpdatedAsync(); + return ret.FirstOrDefault(); + } - [HttpPatch("{id}")] - async public Task UpdateDiy([FromRoute] int id, [FromForm] string title) { - var up = _fsql.Update().Where(a => a.Id == id); - if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title); - var ret = await up.ExecuteUpdatedAsync(); - return ret.FirstOrDefault(); - } + [HttpPatch("{id}")] + async public Task UpdateDiy([FromRoute] int id, [FromForm] string title) + { + var up = _fsql.Update().Where(a => a.Id == id); + if (!string.IsNullOrEmpty(title)) up.Set(a => a.Title, title); + var ret = await up.ExecuteUpdatedAsync(); + return ret.FirstOrDefault(); + } - [HttpDelete("{id}"), ProducesResponseType(204)] - async public Task Delete([FromRoute] int id) { - var ret = await _fsql.Delete().Where(a => a.Id == id).ExecuteDeletedAsync(); - return ret.FirstOrDefault(); - } - } + [HttpDelete("{id}"), ProducesResponseType(204)] + async public Task Delete([FromRoute] int id) + { + var ret = await _fsql.Delete().Where(a => a.Id == id).ExecuteDeletedAsync(); + return ret.FirstOrDefault(); + } + } } diff --git a/Examples/restful/Entitys/Song.cs b/Examples/restful/Entitys/Song.cs index f91f2505..3c85aae1 100644 --- a/Examples/restful/Entitys/Song.cs +++ b/Examples/restful/Entitys/Song.cs @@ -1,10 +1,12 @@ using FreeSql.DataAnnotations; -namespace restful.Entitys { - public class Song { +namespace restful.Entitys +{ + public class Song + { - [Column(IsIdentity = true)] - public int Id { get; set; } - public string Title { get; set; } - } + [Column(IsIdentity = true)] + public int Id { get; set; } + public string Title { get; set; } + } } diff --git a/Examples/restful/Properties/launchSettings.json b/Examples/restful/Properties/launchSettings.json index 06b7366a..789f1c93 100644 --- a/Examples/restful/Properties/launchSettings.json +++ b/Examples/restful/Properties/launchSettings.json @@ -1,27 +1,27 @@ { - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:49778/", - "sslPort": 0 - } - }, - "profiles": { - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:49778/", + "sslPort": 0 + } }, - "FreeSql.RESTful.Demo": { - "commandName": "Project", - "launchBrowser": true, - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "applicationUrl": "http://localhost:49779/" + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "FreeSql.RESTful.Demo": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:49779/" + } } - } } \ No newline at end of file diff --git a/Examples/restful/Startup.cs b/Examples/restful/Startup.cs index 88b7777d..89e8977e 100644 --- a/Examples/restful/Startup.cs +++ b/Examples/restful/Startup.cs @@ -7,61 +7,71 @@ using Swashbuckle.AspNetCore.Swagger; using System; using System.Text; -namespace restful { - public class Startup { - public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { - Configuration = configuration; +namespace restful +{ + public class Startup + { + public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) + { + Configuration = configuration; - Fsql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .Build(); + Fsql = new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .Build(); - Fsql.Aop.CurdAfter = (s, e) => { - if (e.ElapsedMilliseconds > 200) { - //记录日志 - //发送短信给负责人 - } - }; + Fsql.Aop.CurdAfter = (s, e) => + { + if (e.ElapsedMilliseconds > 200) + { + //记录日志 + //发送短信给负责人 + } + }; - //Fsql.Aop.Where = (s, e) => { - // if (e.Parameters[0]?.ToString() == "1") - // e.IsCancel = true; - //}; - } + //Fsql.Aop.Where = (s, e) => { + // if (e.Parameters[0]?.ToString() == "1") + // e.IsCancel = true; + //}; + } - public IConfiguration Configuration { get; } - public IFreeSql Fsql { get; } + public IConfiguration Configuration { get; } + public IFreeSql Fsql { get; } - public void ConfigureServices(IServiceCollection services) { - services.AddSingleton(Fsql); + public void ConfigureServices(IServiceCollection services) + { + services.AddSingleton(Fsql); - services.AddMvc(); - services.AddSwaggerGen(options => { - options.SwaggerDoc("v1", new Info { - Version = "v1", - Title = "FreeSql.RESTful API" - }); - //options.IncludeXmlComments(xmlPath); - }); - } + services.AddMvc(); + services.AddSwaggerGen(options => + { + options.SwaggerDoc("v1", new Info + { + Version = "v1", + Title = "FreeSql.RESTful API" + }); + //options.IncludeXmlComments(xmlPath); + }); + } - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - Console.OutputEncoding = Encoding.GetEncoding("GB2312"); - Console.InputEncoding = Encoding.GetEncoding("GB2312"); + public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + Console.OutputEncoding = Encoding.GetEncoding("GB2312"); + Console.InputEncoding = Encoding.GetEncoding("GB2312"); - loggerFactory.AddConsole(Configuration.GetSection("Logging")); - loggerFactory.AddDebug(); + loggerFactory.AddConsole(Configuration.GetSection("Logging")); + loggerFactory.AddDebug(); - app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" }); - app.UseDeveloperExceptionPage(); - app.UseMvc(); + app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" }); + app.UseDeveloperExceptionPage(); + app.UseMvc(); - app.UseSwagger(); - app.UseSwaggerUI(c => { - c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1"); - }); - } - } + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "FreeSql.RESTful API V1"); + }); + } + } } diff --git a/Examples/restful/appsettings.Development.json b/Examples/restful/appsettings.Development.json index e203e940..6ba02f3f 100644 --- a/Examples/restful/appsettings.Development.json +++ b/Examples/restful/appsettings.Development.json @@ -1,9 +1,9 @@ { - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } } - } } diff --git a/Examples/restful/appsettings.json b/Examples/restful/appsettings.json index def9159a..6d451ac2 100644 --- a/Examples/restful/appsettings.json +++ b/Examples/restful/appsettings.json @@ -1,8 +1,8 @@ { - "Logging": { - "LogLevel": { - "Default": "Warning" - } - }, - "AllowedHosts": "*" + "Logging": { + "LogLevel": { + "Default": "Warning" + } + }, + "AllowedHosts": "*" } diff --git a/Extensions/FreeSql.Extensions.LazyLoading/LazyLoadingComplier.cs b/Extensions/FreeSql.Extensions.LazyLoading/LazyLoadingComplier.cs index 90ebbd32..dc388bf4 100644 --- a/Extensions/FreeSql.Extensions.LazyLoading/LazyLoadingComplier.cs +++ b/Extensions/FreeSql.Extensions.LazyLoading/LazyLoadingComplier.cs @@ -5,30 +5,34 @@ using System.Collections.Generic; using System.Reflection; using System.Text; -namespace FreeSql.Extensions.LazyLoading { +namespace FreeSql.Extensions.LazyLoading +{ - public class LazyLoadingComplier { + public class LazyLoadingComplier + { #if ns20 - internal static Lazy _compiler = new Lazy(() => { - //var dlls = Directory.GetFiles(Directory.GetParent(Type.GetType("IFreeSql, FreeSql").Assembly.Location).FullName, "*.dll"); - var compiler = new CSScriptLib.RoslynEvaluator(); - compiler.DisableReferencingFromCode = false; - //compiler.DebugBuild = true; - //foreach (var dll in dlls) { - // Console.WriteLine(dll); - // var ass = Assembly.LoadFile(dll); - // compiler.ReferenceAssembly(ass); - //} - compiler - .ReferenceAssemblyOf() - .ReferenceDomainAssemblies(); - return compiler; - }); + internal static Lazy _compiler = new Lazy(() => + { + //var dlls = Directory.GetFiles(Directory.GetParent(Type.GetType("IFreeSql, FreeSql").Assembly.Location).FullName, "*.dll"); + var compiler = new CSScriptLib.RoslynEvaluator(); + compiler.DisableReferencingFromCode = false; + //compiler.DebugBuild = true; + //foreach (var dll in dlls) { + // Console.WriteLine(dll); + // var ass = Assembly.LoadFile(dll); + // compiler.ReferenceAssembly(ass); + //} + compiler + .ReferenceAssemblyOf() + .ReferenceDomainAssemblies(); + return compiler; + }); - public static Assembly CompileCode(string cscode) { - return _compiler.Value.CompileCode(cscode); - } + public static Assembly CompileCode(string cscode) + { + return _compiler.Value.CompileCode(cscode); + } #else @@ -52,5 +56,5 @@ namespace FreeSql.Extensions.LazyLoading { } #endif - } + } } diff --git a/FreeSql.DbContext/DbContext/DbContext.cs b/FreeSql.DbContext/DbContext/DbContext.cs index 90625e87..6c6867d7 100644 --- a/FreeSql.DbContext/DbContext/DbContext.cs +++ b/FreeSql.DbContext/DbContext/DbContext.cs @@ -5,150 +5,168 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; -namespace FreeSql { - public abstract partial class DbContext : IDisposable { +namespace FreeSql +{ + public abstract partial class DbContext : IDisposable + { - internal IFreeSql _orm; - internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql"); + internal IFreeSql _orm; + internal IFreeSql _fsql => _orm ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql"); - public IFreeSql Orm => _fsql; + public IFreeSql Orm => _fsql; - protected IUnitOfWork _uowPriv; - internal IUnitOfWork _uow => _isUseUnitOfWork ? (_uowPriv ?? (_uowPriv = new UnitOfWork(_fsql))) : null; - internal bool _isUseUnitOfWork = true; //不使用工作单元事务 + protected IUnitOfWork _uowPriv; + internal IUnitOfWork _uow => _isUseUnitOfWork ? (_uowPriv ?? (_uowPriv = new UnitOfWork(_fsql))) : null; + internal bool _isUseUnitOfWork = true; //不使用工作单元事务 - public IUnitOfWork UnitOfWork => _uow; + public IUnitOfWork UnitOfWork => _uow; - DbContextOptions _options; - internal DbContextOptions Options { - get { - if (_options != null) return _options; - if (FreeSqlDbContextExtenssions._dicSetDbContextOptions.TryGetValue(Orm, out _options)) return _options; - _options = new DbContextOptions(); - return _options; - } - } + DbContextOptions _options; + internal DbContextOptions Options + { + get + { + if (_options != null) return _options; + if (FreeSqlDbContextExtenssions._dicSetDbContextOptions.TryGetValue(Orm, out _options)) return _options; + _options = new DbContextOptions(); + return _options; + } + } - static ConcurrentDictionary _dicGetDbSetProps = new ConcurrentDictionary(); - protected DbContext() { + static ConcurrentDictionary _dicGetDbSetProps = new ConcurrentDictionary(); + protected DbContext() + { - var builder = new DbContextOptionsBuilder(); - OnConfiguring(builder); - _orm = builder._fsql; + var builder = new DbContextOptionsBuilder(); + OnConfiguring(builder); + _orm = builder._fsql; - if (_orm != null) InitPropSets(); - } + if (_orm != null) InitPropSets(); + } - internal void InitPropSets() { - var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp => - tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public) - .Where(a => a.PropertyType.IsGenericType && - a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray()); + internal void InitPropSets() + { + var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp => + tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public) + .Where(a => a.PropertyType.IsGenericType && + a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray()); - foreach (var prop in props) { - var set = this.Set(prop.PropertyType.GenericTypeArguments[0]); + foreach (var prop in props) + { + var set = this.Set(prop.PropertyType.GenericTypeArguments[0]); - prop.SetValue(this, set); - AllSets.Add(prop.Name, set); - } - } + prop.SetValue(this, set); + AllSets.Add(prop.Name, set); + } + } - protected virtual void OnConfiguring(DbContextOptionsBuilder builder) { - - } + protected virtual void OnConfiguring(DbContextOptionsBuilder builder) + { - protected Dictionary _dicSet = new Dictionary(); - public DbSet Set() where TEntity : class => this.Set(typeof(TEntity)) as DbSet; - public virtual IDbSet Set(Type entityType) { - if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType]; - var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(entityType), this) as IDbSet; - if (entityType != typeof(object)) _dicSet.Add(entityType, sd); - return sd; - } - protected Dictionary AllSets { get; } = new Dictionary(); + } - #region DbSet 快速代理 - /// - /// 添加 - /// - /// - /// - public void Add(TEntity data) where TEntity : class => this.Set().Add(data); - public void AddRange(IEnumerable data) where TEntity : class => this.Set().AddRange(data); - public Task AddAsync(TEntity data) where TEntity : class => this.Set().AddAsync(data); - public Task AddRangeAsync(IEnumerable data) where TEntity : class => this.Set().AddRangeAsync(data); + protected Dictionary _dicSet = new Dictionary(); + public DbSet Set() where TEntity : class => this.Set(typeof(TEntity)) as DbSet; + public virtual IDbSet Set(Type entityType) + { + if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType]; + var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(entityType), this) as IDbSet; + if (entityType != typeof(object)) _dicSet.Add(entityType, sd); + return sd; + } + protected Dictionary AllSets { get; } = new Dictionary(); - /// - /// 更新 - /// - /// - /// - public void Update(TEntity data) where TEntity : class => this.Set().Update(data); - public void UpdateRange(IEnumerable data) where TEntity : class => this.Set().UpdateRange(data); - public Task UpdateAsync(TEntity data) where TEntity : class => this.Set().UpdateAsync(data); - public Task UpdateRangeAsync(IEnumerable data) where TEntity : class => this.Set().UpdateRangeAsync(data); + #region DbSet 快速代理 + /// + /// 添加 + /// + /// + /// + public void Add(TEntity data) where TEntity : class => this.Set().Add(data); + public void AddRange(IEnumerable data) where TEntity : class => this.Set().AddRange(data); + public Task AddAsync(TEntity data) where TEntity : class => this.Set().AddAsync(data); + public Task AddRangeAsync(IEnumerable data) where TEntity : class => this.Set().AddRangeAsync(data); - /// - /// 删除 - /// - /// - /// - public void Remove(TEntity data) where TEntity : class => this.Set().Remove(data); - public void RemoveRange(IEnumerable data) where TEntity : class => this.Set().RemoveRange(data); + /// + /// 更新 + /// + /// + /// + public void Update(TEntity data) where TEntity : class => this.Set().Update(data); + public void UpdateRange(IEnumerable data) where TEntity : class => this.Set().UpdateRange(data); + public Task UpdateAsync(TEntity data) where TEntity : class => this.Set().UpdateAsync(data); + public Task UpdateRangeAsync(IEnumerable data) where TEntity : class => this.Set().UpdateRangeAsync(data); - /// - /// 添加或更新 - /// - /// - /// - public void AddOrUpdate(TEntity data) where TEntity : class => this.Set().AddOrUpdate(data); - public Task AddOrUpdateAsync(TEntity data) where TEntity : class => this.Set().AddOrUpdateAsync(data); + /// + /// 删除 + /// + /// + /// + public void Remove(TEntity data) where TEntity : class => this.Set().Remove(data); + public void RemoveRange(IEnumerable data) where TEntity : class => this.Set().RemoveRange(data); - /// - /// 附加实体,可用于不查询就更新或删除 - /// - /// - /// - public void Attach(TEntity data) where TEntity : class => this.Set().Attach(data); - public void AttachRange(IEnumerable data) where TEntity : class => this.Set().AttachRange(data); - #endregion + /// + /// 添加或更新 + /// + /// + /// + public void AddOrUpdate(TEntity data) where TEntity : class => this.Set().AddOrUpdate(data); + public Task AddOrUpdateAsync(TEntity data) where TEntity : class => this.Set().AddOrUpdateAsync(data); - internal class ExecCommandInfo { - public ExecCommandInfoType actionType { get; set; } - public IDbSet dbSet { get; set; } - public Type stateType { get; set; } - public object state { get; set; } - } - internal enum ExecCommandInfoType { Insert, Update, Delete } - Queue _actions = new Queue(); - internal int _affrows = 0; + /// + /// 附加实体,可用于不查询就更新或删除 + /// + /// + /// + public void Attach(TEntity data) where TEntity : class => this.Set().Attach(data); + public void AttachRange(IEnumerable data) where TEntity : class => this.Set().AttachRange(data); + #endregion - internal void EnqueueAction(ExecCommandInfoType actionType, IDbSet dbSet, Type stateType, object state) { - _actions.Enqueue(new ExecCommandInfo { actionType = actionType, dbSet = dbSet, stateType = stateType, state = state }); - } + internal class ExecCommandInfo + { + public ExecCommandInfoType actionType { get; set; } + public IDbSet dbSet { get; set; } + public Type stateType { get; set; } + public object state { get; set; } + } + internal enum ExecCommandInfoType { Insert, Update, Delete } + Queue _actions = new Queue(); + internal int _affrows = 0; - ~DbContext() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - try { - _actions.Clear(); + internal void EnqueueAction(ExecCommandInfoType actionType, IDbSet dbSet, Type stateType, object state) + { + _actions.Enqueue(new ExecCommandInfo { actionType = actionType, dbSet = dbSet, stateType = stateType, state = state }); + } - foreach (var set in _dicSet) - try { - set.Value.Dispose(); - } catch { } + ~DbContext() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + try + { + _actions.Clear(); - _dicSet.Clear(); - AllSets.Clear(); - - _uow?.Rollback(); - } finally { - _isdisposed = true; - GC.SuppressFinalize(this); - } - } - } + foreach (var set in _dicSet) + try + { + set.Value.Dispose(); + } + catch { } + + _dicSet.Clear(); + AllSets.Clear(); + + _uow?.Rollback(); + } + finally + { + _isdisposed = true; + GC.SuppressFinalize(this); + } + } + } } diff --git a/FreeSql.DbContext/DbContext/DbContextAsync.cs b/FreeSql.DbContext/DbContext/DbContextAsync.cs index 269486f9..50deeacd 100644 --- a/FreeSql.DbContext/DbContext/DbContextAsync.cs +++ b/FreeSql.DbContext/DbContext/DbContextAsync.cs @@ -5,115 +5,133 @@ using System.Reflection; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - partial class DbContext { +namespace FreeSql +{ + partial class DbContext + { - async public virtual Task SaveChangesAsync() { - await ExecCommandAsync(); - _uow?.Commit(); - var ret = _affrows; - _affrows = 0; - return ret; - } + async public virtual Task SaveChangesAsync() + { + await ExecCommandAsync(); + _uow?.Commit(); + var ret = _affrows; + _affrows = 0; + return ret; + } - static Dictionary>>> _dicExecCommandDbContextBetchAsync = new Dictionary>>>(); - async internal Task ExecCommandAsync() { - if (isExecCommanding) return; - if (_actions.Any() == false) return; - isExecCommanding = true; + static Dictionary>>> _dicExecCommandDbContextBetchAsync = new Dictionary>>>(); + async internal Task ExecCommandAsync() + { + if (isExecCommanding) return; + if (_actions.Any() == false) return; + isExecCommanding = true; - ExecCommandInfo oldinfo = null; - var states = new List(); + ExecCommandInfo oldinfo = null; + var states = new List(); - Func> dbContextBetch = methodName => { - if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false) - trydic = new Dictionary>>(); - if (trydic.TryGetValue(methodName, out var tryfunc) == false) { - var arrType = oldinfo.stateType.MakeArrayType(); - var dbsetType = oldinfo.dbSet.GetType().BaseType; - var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null); + Func> dbContextBetch = methodName => + { + if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false) + trydic = new Dictionary>>(); + if (trydic.TryGetValue(methodName, out var tryfunc) == false) + { + var arrType = oldinfo.stateType.MakeArrayType(); + var dbsetType = oldinfo.dbSet.GetType().BaseType; + var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null); - var returnTarget = Expression.Label(typeof(Task)); - var parm1DbSet = Expression.Parameter(typeof(object)); - var parm2Vals = Expression.Parameter(typeof(object[])); - var var1Vals = Expression.Variable(arrType); - tryfunc = Expression.Lambda>>(Expression.Block( - new[] { var1Vals }, - Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)), - Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)), - Expression.Label(returnTarget, Expression.Default(typeof(Task))) - ), new[] { parm1DbSet, parm2Vals }).Compile(); - trydic.Add(methodName, tryfunc); - } - return tryfunc(oldinfo.dbSet, states.ToArray()); - }; - Func funcDelete = async () => { - _affrows += await dbContextBetch("DbContextBetchRemoveAsync"); - states.Clear(); - }; - Func funcInsert = async () => { - _affrows += await dbContextBetch("DbContextBetchAddAsync"); - states.Clear(); - }; - Func funcUpdate = async (isLiveUpdate) => { - var affrows = 0; - if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync"); - else affrows = await dbContextBetch("DbContextBetchUpdateAsync"); - if (affrows == -999) { //最后一个元素已被删除 - states.RemoveAt(states.Count - 1); - return; - } - if (affrows == -998 || affrows == -997) { //没有执行更新 - var laststate = states[states.Count - 1]; - states.Clear(); - if (affrows == -997) states.Add(laststate); //保留最后一个 - } - if (affrows > 0) { - _affrows += affrows; - var islastNotUpdated = states.Count != affrows; - var laststate = states[states.Count - 1]; - states.Clear(); - if (islastNotUpdated) states.Add(laststate); //保留最后一个 - } - }; + var returnTarget = Expression.Label(typeof(Task)); + var parm1DbSet = Expression.Parameter(typeof(object)); + var parm2Vals = Expression.Parameter(typeof(object[])); + var var1Vals = Expression.Variable(arrType); + tryfunc = Expression.Lambda>>(Expression.Block( + new[] { var1Vals }, + Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)), + Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)), + Expression.Label(returnTarget, Expression.Default(typeof(Task))) + ), new[] { parm1DbSet, parm2Vals }).Compile(); + trydic.Add(methodName, tryfunc); + } + return tryfunc(oldinfo.dbSet, states.ToArray()); + }; + Func funcDelete = async () => + { + _affrows += await dbContextBetch("DbContextBetchRemoveAsync"); + states.Clear(); + }; + Func funcInsert = async () => + { + _affrows += await dbContextBetch("DbContextBetchAddAsync"); + states.Clear(); + }; + Func funcUpdate = async (isLiveUpdate) => + { + var affrows = 0; + if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync"); + else affrows = await dbContextBetch("DbContextBetchUpdateAsync"); + if (affrows == -999) + { //最后一个元素已被删除 + states.RemoveAt(states.Count - 1); + return; + } + if (affrows == -998 || affrows == -997) + { //没有执行更新 + var laststate = states[states.Count - 1]; + states.Clear(); + if (affrows == -997) states.Add(laststate); //保留最后一个 + } + if (affrows > 0) + { + _affrows += affrows; + var islastNotUpdated = states.Count != affrows; + var laststate = states[states.Count - 1]; + states.Clear(); + if (islastNotUpdated) states.Add(laststate); //保留最后一个 + } + }; - while (_actions.Any() || states.Any()) { - var info = _actions.Any() ? _actions.Dequeue() : null; - if (oldinfo == null) oldinfo = info; - var isLiveUpdate = false; + while (_actions.Any() || states.Any()) + { + var info = _actions.Any() ? _actions.Dequeue() : null; + if (oldinfo == null) oldinfo = info; + var isLiveUpdate = false; - if (_actions.Any() == false && states.Any() || - info != null && oldinfo.actionType != info.actionType || - info != null && oldinfo.stateType != info.stateType) { + if (_actions.Any() == false && states.Any() || + info != null && oldinfo.actionType != info.actionType || + info != null && oldinfo.stateType != info.stateType) + { - if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) { - //最后一个,合起来发送 - states.Add(info.state); - info = null; - } + if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) + { + //最后一个,合起来发送 + states.Add(info.state); + info = null; + } - switch (oldinfo.actionType) { - case ExecCommandInfoType.Insert: - await funcInsert(); - break; - case ExecCommandInfoType.Delete: - await funcDelete(); - break; - } - isLiveUpdate = true; - } + switch (oldinfo.actionType) + { + case ExecCommandInfoType.Insert: + await funcInsert(); + break; + case ExecCommandInfoType.Delete: + await funcDelete(); + break; + } + isLiveUpdate = true; + } - if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) { - if (states.Any()) - await funcUpdate(isLiveUpdate); - } + if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) + { + if (states.Any()) + await funcUpdate(isLiveUpdate); + } - if (info != null) { - states.Add(info.state); - oldinfo = info; - } - } - isExecCommanding = false; - } - } + if (info != null) + { + states.Add(info.state); + oldinfo = info; + } + } + isExecCommanding = false; + } + } } diff --git a/FreeSql.DbContext/DbContext/DbContextOptions.cs b/FreeSql.DbContext/DbContext/DbContextOptions.cs index 47095091..9ff21d0c 100644 --- a/FreeSql.DbContext/DbContext/DbContextOptions.cs +++ b/FreeSql.DbContext/DbContext/DbContextOptions.cs @@ -1,10 +1,12 @@  -namespace FreeSql { - public class DbContextOptions { +namespace FreeSql +{ + public class DbContextOptions + { - /// - /// 是否开启一对多,联级保存功能 - /// - public bool EnableAddOrUpdateNavigateList { get; set; } = true; - } + /// + /// 是否开启一对多,联级保存功能 + /// + public bool EnableAddOrUpdateNavigateList { get; set; } = true; + } } diff --git a/FreeSql.DbContext/DbContext/DbContextOptionsBuilder.cs b/FreeSql.DbContext/DbContext/DbContextOptionsBuilder.cs index a003f65d..0801cfe2 100644 --- a/FreeSql.DbContext/DbContext/DbContextOptionsBuilder.cs +++ b/FreeSql.DbContext/DbContext/DbContextOptionsBuilder.cs @@ -1,13 +1,16 @@  -namespace FreeSql { - public class DbContextOptionsBuilder { +namespace FreeSql +{ + public class DbContextOptionsBuilder + { - internal IFreeSql _fsql; + internal IFreeSql _fsql; - public DbContextOptionsBuilder UseFreeSql(IFreeSql orm) { - _fsql = orm; - return this; - } - } + public DbContextOptionsBuilder UseFreeSql(IFreeSql orm) + { + _fsql = orm; + return this; + } + } } diff --git a/FreeSql.DbContext/DbContext/DbContextSync.cs b/FreeSql.DbContext/DbContext/DbContextSync.cs index 6eec203b..65a00f16 100644 --- a/FreeSql.DbContext/DbContext/DbContextSync.cs +++ b/FreeSql.DbContext/DbContext/DbContextSync.cs @@ -4,116 +4,134 @@ using System.Linq; using System.Reflection; using System.Linq.Expressions; -namespace FreeSql { - partial class DbContext { +namespace FreeSql +{ + partial class DbContext + { - public virtual int SaveChanges() { - ExecCommand(); - _uow?.Commit(); - var ret = _affrows; - _affrows = 0; - return ret; - } + public virtual int SaveChanges() + { + ExecCommand(); + _uow?.Commit(); + var ret = _affrows; + _affrows = 0; + return ret; + } - static Dictionary>> _dicExecCommandDbContextBetch = new Dictionary>>(); - bool isExecCommanding = false; - internal void ExecCommand() { - if (isExecCommanding) return; - if (_actions.Any() == false) return; - isExecCommanding = true; + static Dictionary>> _dicExecCommandDbContextBetch = new Dictionary>>(); + bool isExecCommanding = false; + internal void ExecCommand() + { + if (isExecCommanding) return; + if (_actions.Any() == false) return; + isExecCommanding = true; - ExecCommandInfo oldinfo = null; - var states = new List(); + ExecCommandInfo oldinfo = null; + var states = new List(); - Func dbContextBetch = methodName => { - if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false) - trydic = new Dictionary>(); - if (trydic.TryGetValue(methodName, out var tryfunc) == false) { - var arrType = oldinfo.stateType.MakeArrayType(); - var dbsetType = oldinfo.dbSet.GetType().BaseType; - var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null); + Func dbContextBetch = methodName => + { + if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false) + trydic = new Dictionary>(); + if (trydic.TryGetValue(methodName, out var tryfunc) == false) + { + var arrType = oldinfo.stateType.MakeArrayType(); + var dbsetType = oldinfo.dbSet.GetType().BaseType; + var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null); - var returnTarget = Expression.Label(typeof(int)); - var parm1DbSet = Expression.Parameter(typeof(object)); - var parm2Vals = Expression.Parameter(typeof(object[])); - var var1Vals = Expression.Variable(arrType); - tryfunc = Expression.Lambda>(Expression.Block( - new[] { var1Vals }, - Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)), - Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)), - Expression.Label(returnTarget, Expression.Default(typeof(int))) - ), new[] { parm1DbSet, parm2Vals }).Compile(); - trydic.Add(methodName, tryfunc); - } - return tryfunc(oldinfo.dbSet, states.ToArray()); - }; - Action funcDelete = () => { - _affrows += dbContextBetch("DbContextBetchRemove"); - states.Clear(); - }; - Action funcInsert = () => { - _affrows += dbContextBetch("DbContextBetchAdd"); - states.Clear(); - }; - Action funcUpdate = isLiveUpdate => { - var affrows = 0; - if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow"); - else affrows = dbContextBetch("DbContextBetchUpdate"); - if (affrows == -999) { //最后一个元素已被删除 - states.RemoveAt(states.Count - 1); - return; - } - if (affrows == -998 || affrows == -997) { //没有执行更新 - var laststate = states[states.Count - 1]; - states.Clear(); - if (affrows == -997) states.Add(laststate); //保留最后一个 - } - if (affrows > 0) { - _affrows += affrows; - var islastNotUpdated = states.Count != affrows; - var laststate = states[states.Count - 1]; - states.Clear(); - if (islastNotUpdated) states.Add(laststate); //保留最后一个 - } - }; + var returnTarget = Expression.Label(typeof(int)); + var parm1DbSet = Expression.Parameter(typeof(object)); + var parm2Vals = Expression.Parameter(typeof(object[])); + var var1Vals = Expression.Variable(arrType); + tryfunc = Expression.Lambda>(Expression.Block( + new[] { var1Vals }, + Expression.Assign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)), + Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)), + Expression.Label(returnTarget, Expression.Default(typeof(int))) + ), new[] { parm1DbSet, parm2Vals }).Compile(); + trydic.Add(methodName, tryfunc); + } + return tryfunc(oldinfo.dbSet, states.ToArray()); + }; + Action funcDelete = () => + { + _affrows += dbContextBetch("DbContextBetchRemove"); + states.Clear(); + }; + Action funcInsert = () => + { + _affrows += dbContextBetch("DbContextBetchAdd"); + states.Clear(); + }; + Action funcUpdate = isLiveUpdate => + { + var affrows = 0; + if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow"); + else affrows = dbContextBetch("DbContextBetchUpdate"); + if (affrows == -999) + { //最后一个元素已被删除 + states.RemoveAt(states.Count - 1); + return; + } + if (affrows == -998 || affrows == -997) + { //没有执行更新 + var laststate = states[states.Count - 1]; + states.Clear(); + if (affrows == -997) states.Add(laststate); //保留最后一个 + } + if (affrows > 0) + { + _affrows += affrows; + var islastNotUpdated = states.Count != affrows; + var laststate = states[states.Count - 1]; + states.Clear(); + if (islastNotUpdated) states.Add(laststate); //保留最后一个 + } + }; - while (_actions.Any() || states.Any()) { - var info = _actions.Any() ? _actions.Dequeue() : null; - if (oldinfo == null) oldinfo = info; - var isLiveUpdate = false; + while (_actions.Any() || states.Any()) + { + var info = _actions.Any() ? _actions.Dequeue() : null; + if (oldinfo == null) oldinfo = info; + var isLiveUpdate = false; - if (_actions.Any() == false && states.Any() || - info != null && oldinfo.actionType != info.actionType || - info != null && oldinfo.stateType != info.stateType) { + if (_actions.Any() == false && states.Any() || + info != null && oldinfo.actionType != info.actionType || + info != null && oldinfo.stateType != info.stateType) + { - if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) { - //最后一个,合起来发送 - states.Add(info.state); - info = null; - } + if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) + { + //最后一个,合起来发送 + states.Add(info.state); + info = null; + } - switch (oldinfo.actionType) { - case ExecCommandInfoType.Insert: - funcInsert(); - break; - case ExecCommandInfoType.Delete: - funcDelete(); - break; - } - isLiveUpdate = true; - } + switch (oldinfo.actionType) + { + case ExecCommandInfoType.Insert: + funcInsert(); + break; + case ExecCommandInfoType.Delete: + funcDelete(); + break; + } + isLiveUpdate = true; + } - if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) { - if (states.Any()) - funcUpdate(isLiveUpdate); - } + if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) + { + if (states.Any()) + funcUpdate(isLiveUpdate); + } - if (info != null) { - states.Add(info.state); - oldinfo = info; - } - } - isExecCommanding = false; - } - } + if (info != null) + { + states.Add(info.state); + oldinfo = info; + } + } + isExecCommanding = false; + } + } } diff --git a/FreeSql.DbContext/DbContext/FreeContext.cs b/FreeSql.DbContext/DbContext/FreeContext.cs index a6b0549d..38e23bc0 100644 --- a/FreeSql.DbContext/DbContext/FreeContext.cs +++ b/FreeSql.DbContext/DbContext/FreeContext.cs @@ -1,10 +1,13 @@  -namespace FreeSql { - public class FreeContext : DbContext { +namespace FreeSql +{ + public class FreeContext : DbContext + { - public FreeContext(IFreeSql orm) { - _orm = orm; - } - } + public FreeContext(IFreeSql orm) + { + _orm = orm; + } + } } diff --git a/FreeSql.DbContext/DbSet/DbSet.cs b/FreeSql.DbContext/DbSet/DbSet.cs index b115f424..dbac00d5 100644 --- a/FreeSql.DbContext/DbSet/DbSet.cs +++ b/FreeSql.DbContext/DbSet/DbSet.cs @@ -8,274 +8,326 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; -namespace FreeSql { +namespace FreeSql +{ - internal class DbContextDbSet : DbSet where TEntity : class { + internal class DbContextDbSet : DbSet where TEntity : class + { - public DbContextDbSet(DbContext ctx) { - _ctx = ctx; - _uow = ctx._uow; - _fsql = ctx._fsql; - } - } + public DbContextDbSet(DbContext ctx) + { + _ctx = ctx; + _uow = ctx._uow; + _fsql = ctx._fsql; + } + } - public interface IDbSet : IDisposable { - Type EntityType { get; } - } - public abstract partial class DbSet : IDbSet where TEntity : class { + public interface IDbSet : IDisposable + { + Type EntityType { get; } + } + public abstract partial class DbSet : IDbSet where TEntity : class + { - internal DbContext _ctx; - internal IUnitOfWork _uow; - internal IFreeSql _fsql; + internal DbContext _ctx; + internal IUnitOfWork _uow; + internal IFreeSql _fsql; - protected virtual ISelect OrmSelect(object dywhere) { - DbContextExecCommand(); //查询前先提交,否则会出脏读 - return _fsql.Select().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction(false)).TrackToList(TrackToList).WhereDynamic(dywhere); - } + protected virtual ISelect OrmSelect(object dywhere) + { + DbContextExecCommand(); //查询前先提交,否则会出脏读 + return _fsql.Select().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction(false)).TrackToList(TrackToList).WhereDynamic(dywhere); + } - ~DbSet() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - try { - this._dicUpdateTimes.Clear(); - this._states.Clear(); - } finally { - _isdisposed = true; - GC.SuppressFinalize(this); - } - } + ~DbSet() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + try + { + this._dicUpdateTimes.Clear(); + this._states.Clear(); + } + finally + { + _isdisposed = true; + GC.SuppressFinalize(this); + } + } - protected virtual IInsert OrmInsert() => _fsql.Insert().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()); - protected virtual IInsert OrmInsert(TEntity data) => _fsql.Insert().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data); - protected virtual IInsert OrmInsert(IEnumerable data) => _fsql.Insert().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data); + protected virtual IInsert OrmInsert() => _fsql.Insert().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()); + protected virtual IInsert OrmInsert(TEntity data) => _fsql.Insert().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data); + protected virtual IInsert OrmInsert(IEnumerable data) => _fsql.Insert().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).AppendData(data); - protected virtual IUpdate OrmUpdate(IEnumerable entitys) => _fsql.Update().AsType(_entityType).SetSource(entitys).WithTransaction(_uow?.GetOrBeginTransaction()); - protected virtual IDelete OrmDelete(object dywhere) => _fsql.Delete().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).WhereDynamic(dywhere); + protected virtual IUpdate OrmUpdate(IEnumerable entitys) => _fsql.Update().AsType(_entityType).SetSource(entitys).WithTransaction(_uow?.GetOrBeginTransaction()); + protected virtual IDelete OrmDelete(object dywhere) => _fsql.Delete().AsType(_entityType).WithTransaction(_uow?.GetOrBeginTransaction()).WhereDynamic(dywhere); - internal void EnqueueToDbContext(DbContext.ExecCommandInfoType actionType, EntityState state) { - _ctx.EnqueueAction(actionType, this, typeof(EntityState), state); - } - internal void IncrAffrows(int affrows) { - _ctx._affrows += affrows; - } + internal void EnqueueToDbContext(DbContext.ExecCommandInfoType actionType, EntityState state) + { + _ctx.EnqueueAction(actionType, this, typeof(EntityState), state); + } + internal void IncrAffrows(int affrows) + { + _ctx._affrows += affrows; + } - internal void TrackToList(object list) { - if (list == null) return; - var ls = list as IList; - if (ls == null) { - var ie = list as IEnumerable; - if (ie == null) return; - foreach (var item in ie) { - if (item == null) return; - var itemType = item.GetType(); - if (itemType == typeof(object)) return; - if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType; - var dbset = _ctx.Set(itemType); - dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list }); - return; - } - return; - } + internal void TrackToList(object list) + { + if (list == null) return; + var ls = list as IList; + if (ls == null) + { + var ie = list as IEnumerable; + if (ie == null) return; + foreach (var item in ie) + { + if (item == null) return; + var itemType = item.GetType(); + if (itemType == typeof(object)) return; + if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType; + var dbset = _ctx.Set(itemType); + dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list }); + return; + } + return; + } - foreach (var item in ls) { - var key = _fsql.GetEntityKeyString(_entityType, item, false); - if (key == null) continue; - _states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => { - _fsql.MapEntityValue(_entityType, item, ov.Value); - ov.Time = DateTime.Now; - return ov; - }); - } - } + foreach (var item in ls) + { + var key = _fsql.GetEntityKeyString(_entityType, item, false); + if (key == null) continue; + _states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => + { + _fsql.MapEntityValue(_entityType, item, ov.Value); + ov.Time = DateTime.Now; + return ov; + }); + } + } - public ISelect Select => this.OrmSelect(null); - public ISelect Where(Expression> exp) => this.OrmSelect(null).Where(exp); - public ISelect WhereIf(bool condition, Expression> exp) => this.OrmSelect(null).WhereIf(condition, exp); + public ISelect Select => this.OrmSelect(null); + public ISelect Where(Expression> exp) => this.OrmSelect(null).Where(exp); + public ISelect WhereIf(bool condition, Expression> exp) => this.OrmSelect(null).WhereIf(condition, exp); - protected ConcurrentDictionary _states = new ConcurrentDictionary(); - internal ConcurrentDictionary _statesInternal => _states; - TableInfo _tablePriv; - protected TableInfo _table => _tablePriv ?? (_tablePriv = _fsql.CodeFirst.GetTableByEntity(_entityType)); - ColumnInfo[] _tableIdentitysPriv; - protected ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray()); - protected Type _entityType = typeof(TEntity); - public Type EntityType => _entityType; + protected ConcurrentDictionary _states = new ConcurrentDictionary(); + internal ConcurrentDictionary _statesInternal => _states; + TableInfo _tablePriv; + protected TableInfo _table => _tablePriv ?? (_tablePriv = _fsql.CodeFirst.GetTableByEntity(_entityType)); + ColumnInfo[] _tableIdentitysPriv; + protected ColumnInfo[] _tableIdentitys => _tableIdentitysPriv ?? (_tableIdentitysPriv = _table.Primarys.Where(a => a.Attribute.IsIdentity).ToArray()); + protected Type _entityType = typeof(TEntity); + public Type EntityType => _entityType; - /// - /// 动态Type,在使用 DbSet<object> 后使用本方法,指定实体类型 - /// - /// - /// - public void AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object"); - if (entityType == _entityType) return; - var newtb = _fsql.CodeFirst.GetTableByEntity(entityType); - _entityType = entityType; - _tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型"); - _tableIdentitysPriv = null; - } + /// + /// 动态Type,在使用 DbSet<object> 后使用本方法,指定实体类型 + /// + /// + /// + public void AsType(Type entityType) + { + if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object"); + if (entityType == _entityType) return; + var newtb = _fsql.CodeFirst.GetTableByEntity(entityType); + _entityType = entityType; + _tablePriv = newtb ?? throw new Exception("DbSet.AsType 参数错误,请传入正确的实体类型"); + _tableIdentitysPriv = null; + } - public class EntityState { - public EntityState(TEntity value, string key) { - this.Value = value; - this.Key = key; - this.Time = DateTime.Now; - } - public TEntity OldValue { get; set; } - public TEntity Value { get; set; } - public string Key { get; set; } - public DateTime Time { get; set; } - } - /// - /// 附加实体,可用于不查询就更新或删除 - /// - /// - public void Attach(TEntity data) => AttachRange(new[] { data }); - public void AttachRange(IEnumerable data) { - if (data == null || data.Any() == false) return; - if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_fsql.GetEntityString(_entityType, data.First())}"); - foreach (var item in data) { - var key = _fsql.GetEntityKeyString(_entityType, item, false); - if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_fsql.GetEntityString(_entityType, item)}"); + public class EntityState + { + public EntityState(TEntity value, string key) + { + this.Value = value; + this.Key = key; + this.Time = DateTime.Now; + } + public TEntity OldValue { get; set; } + public TEntity Value { get; set; } + public string Key { get; set; } + public DateTime Time { get; set; } + } + /// + /// 附加实体,可用于不查询就更新或删除 + /// + /// + public void Attach(TEntity data) => AttachRange(new[] { data }); + public void AttachRange(IEnumerable data) + { + if (data == null || data.Any() == false) return; + if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_fsql.GetEntityString(_entityType, data.First())}"); + foreach (var item in data) + { + var key = _fsql.GetEntityKeyString(_entityType, item, false); + if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_fsql.GetEntityString(_entityType, item)}"); - _states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => { - _fsql.MapEntityValue(_entityType, item, ov.Value); - ov.Time = DateTime.Now; - return ov; - }); - } - } - /// - /// 清空状态数据 - /// - public void FlushState() { - _states.Clear(); - } + _states.AddOrUpdate(key, k => CreateEntityState(item), (k, ov) => + { + _fsql.MapEntityValue(_entityType, item, ov.Value); + ov.Time = DateTime.Now; + return ov; + }); + } + } + /// + /// 清空状态数据 + /// + public void FlushState() + { + _states.Clear(); + } - #region Utils - EntityState CreateEntityState(TEntity data) { - if (data == null) throw new ArgumentNullException(nameof(data)); - var key = _fsql.GetEntityKeyString(_entityType, data, false); - var state = new EntityState((TEntity)Activator.CreateInstance(_entityType), key); - _fsql.MapEntityValue(_entityType, data, state.Value); - return state; - } - bool? ExistsInStates(TEntity data) { - if (data == null) throw new ArgumentNullException(nameof(data)); - var key = _fsql.GetEntityKeyString(_entityType, data, false); - if (string.IsNullOrEmpty(key)) return null; - return _states.ContainsKey(key); - } + #region Utils + EntityState CreateEntityState(TEntity data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + var key = _fsql.GetEntityKeyString(_entityType, data, false); + var state = new EntityState((TEntity)Activator.CreateInstance(_entityType), key); + _fsql.MapEntityValue(_entityType, data, state.Value); + return state; + } + bool? ExistsInStates(TEntity data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + var key = _fsql.GetEntityKeyString(_entityType, data, false); + if (string.IsNullOrEmpty(key)) return null; + return _states.ContainsKey(key); + } - bool CanAdd(IEnumerable data, bool isThrow) { - if (data == null) { - if (isThrow) throw new ArgumentNullException(nameof(data)); - return false; - } - if (data.Any() == false) return false; - foreach (var s in data) if (CanAdd(s, isThrow) == false) return false; - return true; - } - bool CanAdd(TEntity data, bool isThrow) { - if (data == null) { - if (isThrow) throw new ArgumentNullException(nameof(data)); - return false; - } - if (_table.Primarys.Any() == false) { - if (isThrow) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - var key = _fsql.GetEntityKeyString(_entityType, data, true); - if (string.IsNullOrEmpty(key)) { - switch (_fsql.Ado.DataType) { - case DataType.SqlServer: - case DataType.PostgreSQL: - return true; - case DataType.MySql: - case DataType.Oracle: - case DataType.Sqlite: - if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) { - return true; - } - if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - } else { - if (_states.ContainsKey(key)) { - if (isThrow) throw new Exception($"不可添加,已存在于状态管理:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - var idval = _fsql.GetEntityIdentityValueWithPrimary(_entityType, data); - if (idval > 0) { - if (isThrow) throw new Exception($"不可添加,自增属性有值:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - } - return true; - } + bool CanAdd(IEnumerable data, bool isThrow) + { + if (data == null) + { + if (isThrow) throw new ArgumentNullException(nameof(data)); + return false; + } + if (data.Any() == false) return false; + foreach (var s in data) if (CanAdd(s, isThrow) == false) return false; + return true; + } + bool CanAdd(TEntity data, bool isThrow) + { + if (data == null) + { + if (isThrow) throw new ArgumentNullException(nameof(data)); + return false; + } + if (_table.Primarys.Any() == false) + { + if (isThrow) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + var key = _fsql.GetEntityKeyString(_entityType, data, true); + if (string.IsNullOrEmpty(key)) + { + switch (_fsql.Ado.DataType) + { + case DataType.SqlServer: + case DataType.PostgreSQL: + return true; + case DataType.MySql: + case DataType.Oracle: + case DataType.Sqlite: + if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) + { + return true; + } + if (isThrow) throw new Exception($"不可添加,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + } + else + { + if (_states.ContainsKey(key)) + { + if (isThrow) throw new Exception($"不可添加,已存在于状态管理:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + var idval = _fsql.GetEntityIdentityValueWithPrimary(_entityType, data); + if (idval > 0) + { + if (isThrow) throw new Exception($"不可添加,自增属性有值:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + } + return true; + } - bool CanUpdate(IEnumerable data, bool isThrow) { - if (data == null) { - if (isThrow) throw new ArgumentNullException(nameof(data)); - return false; - } - if (data.Any() == false) return false; - foreach (var s in data) if (CanUpdate(s, isThrow) == false) return false; - return true; - } - bool CanUpdate(TEntity data, bool isThrow) { - if (data == null) { - if (isThrow) throw new ArgumentNullException(nameof(data)); - return false; - } - if (_table.Primarys.Any() == false) { - if (isThrow) throw new Exception($"不可更新,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - var key = _fsql.GetEntityKeyString(_entityType, data, false); - if (string.IsNullOrEmpty(key)) { - if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - if (_states.TryGetValue(key, out var tryval) == false) { - if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询 或者 Attach:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - return true; - } + bool CanUpdate(IEnumerable data, bool isThrow) + { + if (data == null) + { + if (isThrow) throw new ArgumentNullException(nameof(data)); + return false; + } + if (data.Any() == false) return false; + foreach (var s in data) if (CanUpdate(s, isThrow) == false) return false; + return true; + } + bool CanUpdate(TEntity data, bool isThrow) + { + if (data == null) + { + if (isThrow) throw new ArgumentNullException(nameof(data)); + return false; + } + if (_table.Primarys.Any() == false) + { + if (isThrow) throw new Exception($"不可更新,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + var key = _fsql.GetEntityKeyString(_entityType, data, false); + if (string.IsNullOrEmpty(key)) + { + if (isThrow) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + if (_states.TryGetValue(key, out var tryval) == false) + { + if (isThrow) throw new Exception($"不可更新,数据未被跟踪,应该先查询 或者 Attach:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + return true; + } - bool CanRemove(IEnumerable data, bool isThrow) { - if (data == null) { - if (isThrow) throw new ArgumentNullException(nameof(data)); - return false; - } - if (data.Any() == false) return false; - foreach (var s in data) if (CanRemove(s, isThrow) == false) return false; - return true; - } - bool CanRemove(TEntity data, bool isThrow) { - if (data == null) { - if (isThrow) throw new ArgumentNullException(nameof(data)); - return false; - } - if (_table.Primarys.Any() == false) { - if (isThrow) throw new Exception($"不可删除,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - var key = _fsql.GetEntityKeyString(_entityType, data, false); - if (string.IsNullOrEmpty(key)) { - if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); - return false; - } - //if (_states.TryGetValue(key, out var tryval) == false) { - // if (isThrow) throw new Exception($"不可删除,数据未被跟踪,应该先查询:{_fsql.GetEntityString(_entityType, data)}"); - // return false; - //} - return true; - } - #endregion - } + bool CanRemove(IEnumerable data, bool isThrow) + { + if (data == null) + { + if (isThrow) throw new ArgumentNullException(nameof(data)); + return false; + } + if (data.Any() == false) return false; + foreach (var s in data) if (CanRemove(s, isThrow) == false) return false; + return true; + } + bool CanRemove(TEntity data, bool isThrow) + { + if (data == null) + { + if (isThrow) throw new ArgumentNullException(nameof(data)); + return false; + } + if (_table.Primarys.Any() == false) + { + if (isThrow) throw new Exception($"不可删除,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + var key = _fsql.GetEntityKeyString(_entityType, data, false); + if (string.IsNullOrEmpty(key)) + { + if (isThrow) throw new Exception($"不可删除,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); + return false; + } + //if (_states.TryGetValue(key, out var tryval) == false) { + // if (isThrow) throw new Exception($"不可删除,数据未被跟踪,应该先查询:{_fsql.GetEntityString(_entityType, data)}"); + // return false; + //} + return true; + } + #endregion + } } diff --git a/FreeSql.DbContext/DbSet/DbSetAsync.cs b/FreeSql.DbContext/DbSet/DbSetAsync.cs index 2b5978f9..309046c8 100644 --- a/FreeSql.DbContext/DbSet/DbSetAsync.cs +++ b/FreeSql.DbContext/DbSet/DbSetAsync.cs @@ -6,263 +6,303 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace FreeSql { - partial class DbSet { +namespace FreeSql +{ + partial class DbSet + { - Task DbContextExecCommandAsync() { - _dicUpdateTimes.Clear(); - return _ctx.ExecCommandAsync(); - } + Task DbContextExecCommandAsync() + { + _dicUpdateTimes.Clear(); + return _ctx.ExecCommandAsync(); + } - async Task DbContextBetchAddAsync(EntityState[] adds) { - if (adds.Any() == false) return 0; - var affrows = await this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrowsAsync(); - return affrows; - } + async Task DbContextBetchAddAsync(EntityState[] adds) + { + if (adds.Any() == false) return 0; + var affrows = await this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrowsAsync(); + return affrows; + } - #region Add - async Task AddPrivAsync(TEntity data, bool isCheck) { - if (isCheck && CanAdd(data, true) == false) return; - if (_tableIdentitys.Length > 0) { - //有自增,马上执行 - switch (_fsql.Ado.DataType) { - case DataType.SqlServer: - case DataType.PostgreSQL: - if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) { - await DbContextExecCommandAsync(); - var idtval = await this.OrmInsert(data).ExecuteIdentityAsync(); - IncrAffrows(1); - _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); - Attach(data); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - await AddOrUpdateNavigateListAsync(data); - } else { - await DbContextExecCommandAsync(); - var newval = (await this.OrmInsert(data).ExecuteInsertedAsync()).First(); - IncrAffrows(1); - _fsql.MapEntityValue(_entityType, newval, data); - Attach(newval); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - await AddOrUpdateNavigateListAsync(data); - } - return; - case DataType.MySql: - case DataType.Oracle: - case DataType.Sqlite: - if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) { - await DbContextExecCommandAsync(); - var idtval = await this.OrmInsert(data).ExecuteIdentityAsync(); - IncrAffrows(1); - _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); - Attach(data); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - await AddOrUpdateNavigateListAsync(data); - } - return; - } - } - EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data)); - Attach(data); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - await AddOrUpdateNavigateListAsync(data); - } - public Task AddAsync(TEntity data) => AddPrivAsync(data, true); - async public Task AddRangeAsync(IEnumerable data) { - if (CanAdd(data, true) == false) return; - if (data.ElementAtOrDefault(1) == default(TEntity)) { - await AddAsync(data.First()); - return; - } - if (_tableIdentitys.Length > 0) { - //有自增,马上执行 - switch (_fsql.Ado.DataType) { - case DataType.SqlServer: - case DataType.PostgreSQL: - await DbContextExecCommandAsync(); - var rets = await this.OrmInsert(data).ExecuteInsertedAsync(); - if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配"); - var idx = 0; - foreach (var s in data) - _fsql.MapEntityValue(_entityType, rets[idx++], s); - IncrAffrows(rets.Count); - AttachRange(rets); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - foreach (var item in data) - await AddOrUpdateNavigateListAsync(item); - return; - case DataType.MySql: - case DataType.Oracle: - case DataType.Sqlite: - foreach (var s in data) - await AddPrivAsync(s, false); - return; - } - } else { - //进入队列,等待 SaveChanges 时执行 - foreach (var item in data) - EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item)); - AttachRange(data); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - foreach (var item in data) - await AddOrUpdateNavigateListAsync(item); - } - } - async Task AddOrUpdateNavigateListAsync(TEntity item) { - Type itemType = null; - foreach (var prop in _table.Properties) { - if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue; - if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue; - var tref = _table.GetTableRef(prop.Key, true); - if (tref == null) continue; + #region Add + async Task AddPrivAsync(TEntity data, bool isCheck) + { + if (isCheck && CanAdd(data, true) == false) return; + if (_tableIdentitys.Length > 0) + { + //有自增,马上执行 + switch (_fsql.Ado.DataType) + { + case DataType.SqlServer: + case DataType.PostgreSQL: + if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) + { + await DbContextExecCommandAsync(); + var idtval = await this.OrmInsert(data).ExecuteIdentityAsync(); + IncrAffrows(1); + _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); + Attach(data); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + await AddOrUpdateNavigateListAsync(data); + } + else + { + await DbContextExecCommandAsync(); + var newval = (await this.OrmInsert(data).ExecuteInsertedAsync()).First(); + IncrAffrows(1); + _fsql.MapEntityValue(_entityType, newval, data); + Attach(newval); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + await AddOrUpdateNavigateListAsync(data); + } + return; + case DataType.MySql: + case DataType.Oracle: + case DataType.Sqlite: + if (_tableIdentitys.Length == 1 && _table.Primarys.Length == 1) + { + await DbContextExecCommandAsync(); + var idtval = await this.OrmInsert(data).ExecuteIdentityAsync(); + IncrAffrows(1); + _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); + Attach(data); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + await AddOrUpdateNavigateListAsync(data); + } + return; + } + } + EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data)); + Attach(data); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + await AddOrUpdateNavigateListAsync(data); + } + public Task AddAsync(TEntity data) => AddPrivAsync(data, true); + async public Task AddRangeAsync(IEnumerable data) + { + if (CanAdd(data, true) == false) return; + if (data.ElementAtOrDefault(1) == default(TEntity)) + { + await AddAsync(data.First()); + return; + } + if (_tableIdentitys.Length > 0) + { + //有自增,马上执行 + switch (_fsql.Ado.DataType) + { + case DataType.SqlServer: + case DataType.PostgreSQL: + await DbContextExecCommandAsync(); + var rets = await this.OrmInsert(data).ExecuteInsertedAsync(); + if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配"); + var idx = 0; + foreach (var s in data) + _fsql.MapEntityValue(_entityType, rets[idx++], s); + IncrAffrows(rets.Count); + AttachRange(rets); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + foreach (var item in data) + await AddOrUpdateNavigateListAsync(item); + return; + case DataType.MySql: + case DataType.Oracle: + case DataType.Sqlite: + foreach (var s in data) + await AddPrivAsync(s, false); + return; + } + } + else + { + //进入队列,等待 SaveChanges 时执行 + foreach (var item in data) + EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item)); + AttachRange(data); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + foreach (var item in data) + await AddOrUpdateNavigateListAsync(item); + } + } + async Task AddOrUpdateNavigateListAsync(TEntity item) + { + Type itemType = null; + foreach (var prop in _table.Properties) + { + if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue; + if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue; + var tref = _table.GetTableRef(prop.Key, true); + if (tref == null) continue; - switch (tref.RefType) { - case Internal.Model.TableRefType.OneToOne: - case Internal.Model.TableRefType.ManyToOne: - case Internal.Model.TableRefType.ManyToMany: - continue; - case Internal.Model.TableRefType.OneToMany: - if (itemType == null) itemType = item.GetType(); - if (_table.TypeLazy != null && itemType == _table.TypeLazy) { - var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary()).GetOrAdd(prop.Key, propName => - _table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)); - if (lazyField != null) { - var lazyFieldValue = (bool)lazyField.GetValue(item); - if (lazyFieldValue == false) continue; - } - } - var propVal = prop.Value.GetValue(item); - var propValEach = propVal as IEnumerable; - if (propValEach == null) continue; - object dbset = null; - System.Reflection.MethodInfo dbsetAddOrUpdate = null; - foreach (var propValItem in propValEach) { - if (dbset == null) { - dbset = _ctx.Set(tref.RefEntityType); - dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEntityType }); - } - for (var colidx = 0; colidx < tref.Columns.Count; colidx++) { - tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName] - .SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item)); - } - Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task; - await task; - } - break; - } - } - } - #endregion + switch (tref.RefType) + { + case Internal.Model.TableRefType.OneToOne: + case Internal.Model.TableRefType.ManyToOne: + case Internal.Model.TableRefType.ManyToMany: + continue; + case Internal.Model.TableRefType.OneToMany: + if (itemType == null) itemType = item.GetType(); + if (_table.TypeLazy != null && itemType == _table.TypeLazy) + { + var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary()).GetOrAdd(prop.Key, propName => + _table.TypeLazy.GetField($"__lazy__{propName}", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)); + if (lazyField != null) + { + var lazyFieldValue = (bool)lazyField.GetValue(item); + if (lazyFieldValue == false) continue; + } + } + var propVal = prop.Value.GetValue(item); + var propValEach = propVal as IEnumerable; + if (propValEach == null) continue; + object dbset = null; + System.Reflection.MethodInfo dbsetAddOrUpdate = null; + foreach (var propValItem in propValEach) + { + if (dbset == null) + { + dbset = _ctx.Set(tref.RefEntityType); + dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdateAsync", new Type[] { tref.RefEntityType }); + } + for (var colidx = 0; colidx < tref.Columns.Count; colidx++) + { + tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName] + .SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item)); + } + Task task = dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }) as Task; + await task; + } + break; + } + } + } + #endregion - #region UpdateAsync - Task DbContextBetchUpdateAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, false); - Task DbContextBetchUpdateNowAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, true); - async Task DbContextBetchUpdatePrivAsync(EntityState[] ups, bool isLiveUpdate) { - if (ups.Any() == false) return 0; - var uplst1 = ups[ups.Length - 1]; - var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null; + #region UpdateAsync + Task DbContextBetchUpdateAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, false); + Task DbContextBetchUpdateNowAsync(EntityState[] ups) => DbContextBetchUpdatePrivAsync(ups, true); + async Task DbContextBetchUpdatePrivAsync(EntityState[] ups, bool isLiveUpdate) + { + if (ups.Any() == false) return 0; + var uplst1 = ups[ups.Length - 1]; + var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null; - if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999; - var lstval2 = default(EntityState); - if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}"); + if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999; + var lstval2 = default(EntityState); + if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}"); - var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true); - var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null; + var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true); + var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null; - List data = null; - string[] cuig = null; - if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) { - //最后一个不保存 - data = ups.ToList(); - data.RemoveAt(ups.Length - 1); - cuig = cuig2; - } else if (isLiveUpdate) { - //立即保存 - data = ups.ToList(); - cuig = cuig1; - } + List data = null; + string[] cuig = null; + if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) + { + //最后一个不保存 + data = ups.ToList(); + data.RemoveAt(ups.Length - 1); + cuig = cuig2; + } + else if (isLiveUpdate) + { + //立即保存 + data = ups.ToList(); + cuig = cuig1; + } - if (data?.Count > 0) { + if (data?.Count > 0) + { - if (cuig.Length == _table.Columns.Count) - return ups.Length == data.Count ? -998 : -997; + if (cuig.Length == _table.Columns.Count) + return ups.Length == data.Count ? -998 : -997; - var updateSource = data.Select(a => a.Value).ToArray(); - var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig); + var updateSource = data.Select(a => a.Value).ToArray(); + var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig); - var affrows = await update.ExecuteAffrowsAsync(); + var affrows = await update.ExecuteAffrowsAsync(); - foreach (var newval in data) { - if (_states.TryGetValue(newval.Key, out var tryold)) - _fsql.MapEntityValue(_entityType, newval.Value, tryold.Value); - if (newval.OldValue != null) - _fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue); - } - return affrows; - } + foreach (var newval in data) + { + if (_states.TryGetValue(newval.Key, out var tryold)) + _fsql.MapEntityValue(_entityType, newval.Value, tryold.Value); + if (newval.OldValue != null) + _fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue); + } + return affrows; + } - //等待下次对比再保存 - return 0; - } - async public Task UpdateAsync(TEntity data) { - var exists = ExistsInStates(data); - if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); - if (exists == false) { - var olddata = await OrmSelect(data).FirstAsync(); - if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}"); - } + //等待下次对比再保存 + return 0; + } + async public Task UpdateAsync(TEntity data) + { + var exists = ExistsInStates(data); + if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); + if (exists == false) + { + var olddata = await OrmSelect(data).FirstAsync(); + if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}"); + } - await UpdateRangePrivAsync(new[] { data }, true); - } - public Task UpdateRangeAsync(IEnumerable data) => UpdateRangePrivAsync(data, true); - async Task UpdateRangePrivAsync(IEnumerable data, bool isCheck) { - if (CanUpdate(data, true) == false) return; - foreach (var item in data) { - if (_dicUpdateTimes.ContainsKey(item)) - await DbContextExecCommandAsync(); - _dicUpdateTimes.Add(item, 1); + await UpdateRangePrivAsync(new[] { data }, true); + } + public Task UpdateRangeAsync(IEnumerable data) => UpdateRangePrivAsync(data, true); + async Task UpdateRangePrivAsync(IEnumerable data, bool isCheck) + { + if (CanUpdate(data, true) == false) return; + foreach (var item in data) + { + if (_dicUpdateTimes.ContainsKey(item)) + await DbContextExecCommandAsync(); + _dicUpdateTimes.Add(item, 1); - var state = CreateEntityState(item); - state.OldValue = item; - EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state); - } - if (_ctx.Options.EnableAddOrUpdateNavigateList) - foreach (var item in data) - await AddOrUpdateNavigateListAsync(item); - } - #endregion + var state = CreateEntityState(item); + state.OldValue = item; + EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state); + } + if (_ctx.Options.EnableAddOrUpdateNavigateList) + foreach (var item in data) + await AddOrUpdateNavigateListAsync(item); + } + #endregion - #region RemoveAsync - async Task DbContextBetchRemoveAsync(EntityState[] dels) { - if (dels.Any() == false) return 0; - var affrows = await this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrowsAsync(); - return Math.Max(dels.Length, affrows); - } - #endregion + #region RemoveAsync + async Task DbContextBetchRemoveAsync(EntityState[] dels) + { + if (dels.Any() == false) return 0; + var affrows = await this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrowsAsync(); + return Math.Max(dels.Length, affrows); + } + #endregion - #region AddOrUpdateAsync - async public Task AddOrUpdateAsync(TEntity data) { - if (data == null) throw new ArgumentNullException(nameof(data)); - if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); + #region AddOrUpdateAsync + async public Task AddOrUpdateAsync(TEntity data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); - var flagExists = ExistsInStates(data); - if (flagExists == false) { - var olddata = await OrmSelect(data).FirstAsync(); - if (olddata == null) flagExists = false; - } + var flagExists = ExistsInStates(data); + if (flagExists == false) + { + var olddata = await OrmSelect(data).FirstAsync(); + if (olddata == null) flagExists = false; + } - if (flagExists == true && CanUpdate(data, false)) { - await DbContextExecCommandAsync(); - var affrows = _ctx._affrows; - await UpdateRangePrivAsync(new[] { data }, false); - await DbContextExecCommandAsync(); - affrows = _ctx._affrows - affrows; - if (affrows > 0) return; - } - if (CanAdd(data, false)) { - _fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data); - await AddPrivAsync(data, false); - } - } - #endregion - } + if (flagExists == true && CanUpdate(data, false)) + { + await DbContextExecCommandAsync(); + var affrows = _ctx._affrows; + await UpdateRangePrivAsync(new[] { data }, false); + await DbContextExecCommandAsync(); + affrows = _ctx._affrows - affrows; + if (affrows > 0) return; + } + if (CanAdd(data, false)) + { + _fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data); + await AddPrivAsync(data, false); + } + } + #endregion + } } diff --git a/FreeSql.DbContext/DbSet/DbSetSync.cs b/FreeSql.DbContext/DbSet/DbSetSync.cs index c41c1d77..b056583b 100644 --- a/FreeSql.DbContext/DbSet/DbSetSync.cs +++ b/FreeSql.DbContext/DbSet/DbSetSync.cs @@ -6,300 +6,344 @@ using System.Collections.Concurrent; using System.Linq; using System.Reflection; -namespace FreeSql { - partial class DbSet { +namespace FreeSql +{ + partial class DbSet + { - void DbContextExecCommand() { - _dicUpdateTimes.Clear(); - _ctx.ExecCommand(); - } + void DbContextExecCommand() + { + _dicUpdateTimes.Clear(); + _ctx.ExecCommand(); + } - int DbContextBetchAdd(EntityState[] adds) { - if (adds.Any() == false) return 0; - var affrows = this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrows(); - return affrows; - } + int DbContextBetchAdd(EntityState[] adds) + { + if (adds.Any() == false) return 0; + var affrows = this.OrmInsert(adds.Select(a => a.Value)).ExecuteAffrows(); + return affrows; + } - #region Add - void AddPriv(TEntity data, bool isCheck) { - if (isCheck && CanAdd(data, true) == false) return; - if (_tableIdentitys.Length > 0) { - //有自增,马上执行 - switch (_fsql.Ado.DataType) { - case DataType.SqlServer: - case DataType.PostgreSQL: - if (_tableIdentitys.Length == 1) { - DbContextExecCommand(); - var idtval = this.OrmInsert(data).ExecuteIdentity(); - IncrAffrows(1); - _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); - Attach(data); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - AddOrUpdateNavigateList(data); - } else { - DbContextExecCommand(); - var newval = this.OrmInsert(data).ExecuteInserted().First(); - IncrAffrows(1); - _fsql.MapEntityValue(_entityType, newval, data); - Attach(newval); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - AddOrUpdateNavigateList(data); - } - return; - case DataType.MySql: - case DataType.Oracle: - case DataType.Sqlite: - if (_tableIdentitys.Length == 1) { - DbContextExecCommand(); - var idtval = this.OrmInsert(data).ExecuteIdentity(); - IncrAffrows(1); - _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); - Attach(data); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - AddOrUpdateNavigateList(data); - } - return; - } - } - EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data)); - Attach(data); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - AddOrUpdateNavigateList(data); - } - /// - /// 添加 - /// - /// - public void Add(TEntity data) => AddPriv(data, true); - public void AddRange(IEnumerable data) { - if (CanAdd(data, true) == false) return; - if (data.ElementAtOrDefault(1) == default(TEntity)) { - Add(data.First()); - return; - } - if (_tableIdentitys.Length > 0) { - //有自增,马上执行 - switch (_fsql.Ado.DataType) { - case DataType.SqlServer: - case DataType.PostgreSQL: - DbContextExecCommand(); - var rets = this.OrmInsert(data).ExecuteInserted(); - if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配"); - var idx = 0; - foreach (var s in data) - _fsql.MapEntityValue(_entityType, rets[idx++], s); - IncrAffrows(rets.Count); - AttachRange(rets); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - foreach (var item in data) - AddOrUpdateNavigateList(item); - return; - case DataType.MySql: - case DataType.Oracle: - case DataType.Sqlite: - foreach (var s in data) - AddPriv(s, false); - return; - } - } else { - //进入队列,等待 SaveChanges 时执行 - foreach (var item in data) - EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item)); - AttachRange(data); - if (_ctx.Options.EnableAddOrUpdateNavigateList) - foreach (var item in data) - AddOrUpdateNavigateList(item); - } - } - static ConcurrentDictionary> _dicLazyIsSetField = new ConcurrentDictionary>(); - void AddOrUpdateNavigateList(TEntity item) { - Type itemType = null; - foreach (var prop in _table.Properties) { - if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue; - if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue; + #region Add + void AddPriv(TEntity data, bool isCheck) + { + if (isCheck && CanAdd(data, true) == false) return; + if (_tableIdentitys.Length > 0) + { + //有自增,马上执行 + switch (_fsql.Ado.DataType) + { + case DataType.SqlServer: + case DataType.PostgreSQL: + if (_tableIdentitys.Length == 1) + { + DbContextExecCommand(); + var idtval = this.OrmInsert(data).ExecuteIdentity(); + IncrAffrows(1); + _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); + Attach(data); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + AddOrUpdateNavigateList(data); + } + else + { + DbContextExecCommand(); + var newval = this.OrmInsert(data).ExecuteInserted().First(); + IncrAffrows(1); + _fsql.MapEntityValue(_entityType, newval, data); + Attach(newval); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + AddOrUpdateNavigateList(data); + } + return; + case DataType.MySql: + case DataType.Oracle: + case DataType.Sqlite: + if (_tableIdentitys.Length == 1) + { + DbContextExecCommand(); + var idtval = this.OrmInsert(data).ExecuteIdentity(); + IncrAffrows(1); + _fsql.SetEntityIdentityValueWithPrimary(_entityType, data, idtval); + Attach(data); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + AddOrUpdateNavigateList(data); + } + return; + } + } + EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(data)); + Attach(data); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + AddOrUpdateNavigateList(data); + } + /// + /// 添加 + /// + /// + public void Add(TEntity data) => AddPriv(data, true); + public void AddRange(IEnumerable data) + { + if (CanAdd(data, true) == false) return; + if (data.ElementAtOrDefault(1) == default(TEntity)) + { + Add(data.First()); + return; + } + if (_tableIdentitys.Length > 0) + { + //有自增,马上执行 + switch (_fsql.Ado.DataType) + { + case DataType.SqlServer: + case DataType.PostgreSQL: + DbContextExecCommand(); + var rets = this.OrmInsert(data).ExecuteInserted(); + if (rets.Count != data.Count()) throw new Exception($"特别错误:批量添加失败,{_fsql.Ado.DataType} 的返回数据,与添加的数目不匹配"); + var idx = 0; + foreach (var s in data) + _fsql.MapEntityValue(_entityType, rets[idx++], s); + IncrAffrows(rets.Count); + AttachRange(rets); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + foreach (var item in data) + AddOrUpdateNavigateList(item); + return; + case DataType.MySql: + case DataType.Oracle: + case DataType.Sqlite: + foreach (var s in data) + AddPriv(s, false); + return; + } + } + else + { + //进入队列,等待 SaveChanges 时执行 + foreach (var item in data) + EnqueueToDbContext(DbContext.ExecCommandInfoType.Insert, CreateEntityState(item)); + AttachRange(data); + if (_ctx.Options.EnableAddOrUpdateNavigateList) + foreach (var item in data) + AddOrUpdateNavigateList(item); + } + } + static ConcurrentDictionary> _dicLazyIsSetField = new ConcurrentDictionary>(); + void AddOrUpdateNavigateList(TEntity item) + { + Type itemType = null; + foreach (var prop in _table.Properties) + { + if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue; + if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue; - object propVal = null; + object propVal = null; - if (itemType == null) itemType = item.GetType(); - if (_table.TypeLazy != null && itemType == _table.TypeLazy) { - var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary()).GetOrAdd(prop.Key, propName => - _table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance)); - if (lazyField != null) { - var lazyFieldValue = (bool)lazyField.GetValue(item); - if (lazyFieldValue == false) continue; - } - propVal = prop.Value.GetValue(item); - } else { - propVal = prop.Value.GetValue(item); - if (propVal == null) continue; - } + if (itemType == null) itemType = item.GetType(); + if (_table.TypeLazy != null && itemType == _table.TypeLazy) + { + var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary()).GetOrAdd(prop.Key, propName => + _table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance)); + if (lazyField != null) + { + var lazyFieldValue = (bool)lazyField.GetValue(item); + if (lazyFieldValue == false) continue; + } + propVal = prop.Value.GetValue(item); + } + else + { + propVal = prop.Value.GetValue(item); + if (propVal == null) continue; + } - var tref = _table.GetTableRef(prop.Key, true); - if (tref == null) continue; + var tref = _table.GetTableRef(prop.Key, true); + if (tref == null) continue; - switch(tref.RefType) { - case Internal.Model.TableRefType.OneToOne: - case Internal.Model.TableRefType.ManyToOne: - case Internal.Model.TableRefType.ManyToMany: - continue; - case Internal.Model.TableRefType.OneToMany: - var propValEach = propVal as IEnumerable; - if (propValEach == null) continue; - object dbset = null; - MethodInfo dbsetAddOrUpdate = null; - foreach (var propValItem in propValEach) { - if (dbset == null) { - dbset = _ctx.Set(tref.RefEntityType); - dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEntityType }); - } - for (var colidx = 0; colidx < tref.Columns.Count; colidx++) { - tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName] - .SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item)); - } - dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }); - } - break; - } - } - } - #endregion + switch (tref.RefType) + { + case Internal.Model.TableRefType.OneToOne: + case Internal.Model.TableRefType.ManyToOne: + case Internal.Model.TableRefType.ManyToMany: + continue; + case Internal.Model.TableRefType.OneToMany: + var propValEach = propVal as IEnumerable; + if (propValEach == null) continue; + object dbset = null; + MethodInfo dbsetAddOrUpdate = null; + foreach (var propValItem in propValEach) + { + if (dbset == null) + { + dbset = _ctx.Set(tref.RefEntityType); + dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEntityType }); + } + for (var colidx = 0; colidx < tref.Columns.Count; colidx++) + { + tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName] + .SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item)); + } + dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem }); + } + break; + } + } + } + #endregion - #region Update - int DbContextBetchUpdate(EntityState[] ups) => DbContextBetchUpdatePriv(ups, false); - int DbContextBetchUpdateNow(EntityState[] ups) => DbContextBetchUpdatePriv(ups, true); - int DbContextBetchUpdatePriv(EntityState[] ups, bool isLiveUpdate) { - if (ups.Any() == false) return 0; - var uplst1 = ups[ups.Length - 1]; - var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null; + #region Update + int DbContextBetchUpdate(EntityState[] ups) => DbContextBetchUpdatePriv(ups, false); + int DbContextBetchUpdateNow(EntityState[] ups) => DbContextBetchUpdatePriv(ups, true); + int DbContextBetchUpdatePriv(EntityState[] ups, bool isLiveUpdate) + { + if (ups.Any() == false) return 0; + var uplst1 = ups[ups.Length - 1]; + var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null; - if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999; - var lstval2 = default(EntityState); - if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}"); + if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999; + var lstval2 = default(EntityState); + if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEntityString(_entityType, uplst2.Value)}"); - var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true); - var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null; + var cuig1 = _fsql.CompareEntityValueReturnColumns(_entityType, uplst1.Value, lstval1.Value, true); + var cuig2 = uplst2 != null ? _fsql.CompareEntityValueReturnColumns(_entityType, uplst2.Value, lstval2.Value, true) : null; - List data = null; - string[] cuig = null; - if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) { - //最后一个不保存 - data = ups.ToList(); - data.RemoveAt(ups.Length - 1); - cuig = cuig2; - } else if (isLiveUpdate) { - //立即保存 - data = ups.ToList(); - cuig = cuig1; - } + List data = null; + string[] cuig = null; + if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) + { + //最后一个不保存 + data = ups.ToList(); + data.RemoveAt(ups.Length - 1); + cuig = cuig2; + } + else if (isLiveUpdate) + { + //立即保存 + data = ups.ToList(); + cuig = cuig1; + } - if (data?.Count > 0) { + if (data?.Count > 0) + { - if (cuig.Length == _table.Columns.Count) - return ups.Length == data.Count ? -998 : -997; + if (cuig.Length == _table.Columns.Count) + return ups.Length == data.Count ? -998 : -997; - var updateSource = data.Select(a => a.Value).ToArray(); - var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig); + var updateSource = data.Select(a => a.Value).ToArray(); + var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig); - var affrows = update.ExecuteAffrows(); + var affrows = update.ExecuteAffrows(); - foreach (var newval in data) { - if (_states.TryGetValue(newval.Key, out var tryold)) - _fsql.MapEntityValue(_entityType, newval.Value, tryold.Value); - if (newval.OldValue != null) - _fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue); - } - return affrows; - } + foreach (var newval in data) + { + if (_states.TryGetValue(newval.Key, out var tryold)) + _fsql.MapEntityValue(_entityType, newval.Value, tryold.Value); + if (newval.OldValue != null) + _fsql.MapEntityValue(_entityType, newval.Value, newval.OldValue); + } + return affrows; + } - //等待下次对比再保存 - return 0; - } + //等待下次对比再保存 + return 0; + } - Dictionary _dicUpdateTimes = new Dictionary(); - /// - /// 更新 - /// - /// - public void Update(TEntity data) { - var exists = ExistsInStates(data); - if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); - if (exists == false) { - var olddata = OrmSelect(data).First(); - if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}"); - } + Dictionary _dicUpdateTimes = new Dictionary(); + /// + /// 更新 + /// + /// + public void Update(TEntity data) + { + var exists = ExistsInStates(data); + if (exists == null) throw new Exception($"不可更新,未设置主键的值:{_fsql.GetEntityString(_entityType, data)}"); + if (exists == false) + { + var olddata = OrmSelect(data).First(); + if (olddata == null) throw new Exception($"不可更新,数据库不存在该记录:{_fsql.GetEntityString(_entityType, data)}"); + } - UpdateRangePriv(new[] { data }, true); - } - public void UpdateRange(IEnumerable data) => UpdateRangePriv(data, true); - void UpdateRangePriv(IEnumerable data, bool isCheck) { - if (CanUpdate(data, true) == false) return; - foreach (var item in data) { - if (_dicUpdateTimes.ContainsKey(item)) - DbContextExecCommand(); - _dicUpdateTimes.Add(item, 1); + UpdateRangePriv(new[] { data }, true); + } + public void UpdateRange(IEnumerable data) => UpdateRangePriv(data, true); + void UpdateRangePriv(IEnumerable data, bool isCheck) + { + if (CanUpdate(data, true) == false) return; + foreach (var item in data) + { + if (_dicUpdateTimes.ContainsKey(item)) + DbContextExecCommand(); + _dicUpdateTimes.Add(item, 1); - var state = CreateEntityState(item); - state.OldValue = item; - EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state); - } - if (_ctx.Options.EnableAddOrUpdateNavigateList) - foreach (var item in data) - AddOrUpdateNavigateList(item); - } - #endregion + var state = CreateEntityState(item); + state.OldValue = item; + EnqueueToDbContext(DbContext.ExecCommandInfoType.Update, state); + } + if (_ctx.Options.EnableAddOrUpdateNavigateList) + foreach (var item in data) + AddOrUpdateNavigateList(item); + } + #endregion - #region Remove - int DbContextBetchRemove(EntityState[] dels) { - if (dels.Any() == false) return 0; - var affrows = this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrows(); - return Math.Max(dels.Length, affrows); - } + #region Remove + int DbContextBetchRemove(EntityState[] dels) + { + if (dels.Any() == false) return 0; + var affrows = this.OrmDelete(dels.Select(a => a.Value)).ExecuteAffrows(); + return Math.Max(dels.Length, affrows); + } - /// - /// 删除 - /// - /// - public void Remove(TEntity data) => RemoveRange(new[] { data }); - public void RemoveRange(IEnumerable data) { - if (CanRemove(data, true) == false) return; - foreach (var item in data) { - var state = CreateEntityState(item); - _states.TryRemove(state.Key, out var trystate); - _fsql.ClearEntityPrimaryValueWithIdentityAndGuid(_entityType, item); + /// + /// 删除 + /// + /// + public void Remove(TEntity data) => RemoveRange(new[] { data }); + public void RemoveRange(IEnumerable data) + { + if (CanRemove(data, true) == false) return; + foreach (var item in data) + { + var state = CreateEntityState(item); + _states.TryRemove(state.Key, out var trystate); + _fsql.ClearEntityPrimaryValueWithIdentityAndGuid(_entityType, item); - EnqueueToDbContext(DbContext.ExecCommandInfoType.Delete, state); - } - } - #endregion + EnqueueToDbContext(DbContext.ExecCommandInfoType.Delete, state); + } + } + #endregion - #region AddOrUpdate - /// - /// 添加或更新 - /// - /// - public void AddOrUpdate(TEntity data) { - if (data == null) throw new ArgumentNullException(nameof(data)); - if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); + #region AddOrUpdate + /// + /// 添加或更新 + /// + /// + public void AddOrUpdate(TEntity data) + { + if (data == null) throw new ArgumentNullException(nameof(data)); + if (_table.Primarys.Any() == false) throw new Exception($"不可添加,实体没有主键:{_fsql.GetEntityString(_entityType, data)}"); - var flagExists = ExistsInStates(data); - if (flagExists == false) { - var olddata = OrmSelect(data).First(); - if (olddata == null) flagExists = false; - } + var flagExists = ExistsInStates(data); + if (flagExists == false) + { + var olddata = OrmSelect(data).First(); + if (olddata == null) flagExists = false; + } - if (flagExists == true && CanUpdate(data, false)) { - DbContextExecCommand(); - var affrows = _ctx._affrows; - UpdateRangePriv(new[] { data }, false); - DbContextExecCommand(); - affrows = _ctx._affrows - affrows; - if (affrows > 0) return; - } - if (CanAdd(data, false)) { - _fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data); - AddPriv(data, false); - } - } - #endregion - } + if (flagExists == true && CanUpdate(data, false)) + { + DbContextExecCommand(); + var affrows = _ctx._affrows; + UpdateRangePriv(new[] { data }, false); + DbContextExecCommand(); + affrows = _ctx._affrows - affrows; + if (affrows > 0) return; + } + if (CanAdd(data, false)) + { + _fsql.ClearEntityPrimaryValueWithIdentity(_entityType, data); + AddPriv(data, false); + } + } + #endregion + } } diff --git a/FreeSql.DbContext/Extenssions/DependencyInjection.cs b/FreeSql.DbContext/Extenssions/DependencyInjection.cs index a91635a5..bf92a08e 100644 --- a/FreeSql.DbContext/Extenssions/DependencyInjection.cs +++ b/FreeSql.DbContext/Extenssions/DependencyInjection.cs @@ -3,30 +3,35 @@ using Microsoft.Extensions.DependencyInjection; using System; -namespace FreeSql { - public static class DbContextDependencyInjection { +namespace FreeSql +{ + public static class DbContextDependencyInjection + { - public static IServiceCollection AddFreeDbContext(this IServiceCollection services, Action options) where TDbContext : DbContext { + public static IServiceCollection AddFreeDbContext(this IServiceCollection services, Action options) where TDbContext : DbContext + { - services.AddScoped(sp => { - var ctx = Activator.CreateInstance(); + services.AddScoped(sp => + { + var ctx = Activator.CreateInstance(); - if (ctx._orm == null) { - var builder = new DbContextOptionsBuilder(); - options(builder); - ctx._orm = builder._fsql; + if (ctx._orm == null) + { + var builder = new DbContextOptionsBuilder(); + options(builder); + ctx._orm = builder._fsql; - if (ctx._orm == null) - throw new Exception("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql"); + if (ctx._orm == null) + throw new Exception("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql"); - ctx.InitPropSets(); - } + ctx.InitPropSets(); + } - return ctx; - }); + return ctx; + }); - return services; - } - } + return services; + } + } } #endif \ No newline at end of file diff --git a/FreeSql.DbContext/Extenssions/FreeSqlDbContextExtenssions.cs b/FreeSql.DbContext/Extenssions/FreeSqlDbContextExtenssions.cs index 7fae5c66..af755db5 100644 --- a/FreeSql.DbContext/Extenssions/FreeSqlDbContextExtenssions.cs +++ b/FreeSql.DbContext/Extenssions/FreeSqlDbContextExtenssions.cs @@ -2,37 +2,41 @@ using System; using System.Collections.Concurrent; -public static class FreeSqlDbContextExtenssions { +public static class FreeSqlDbContextExtenssions +{ - /// - /// 创建普通数据上下文档对象 - /// - /// - /// - public static DbContext CreateDbContext(this IFreeSql that) { - return new FreeContext(that); - } + /// + /// 创建普通数据上下文档对象 + /// + /// + /// + public static DbContext CreateDbContext(this IFreeSql that) + { + return new FreeContext(that); + } - /// - /// 不跟踪查询的实体数据(在不需要更新其数据时使用),可提长查询性能 - /// - /// - /// - /// - public static ISelect NoTracking(this ISelect select) where T : class { - return select.TrackToList(null); - } + /// + /// 不跟踪查询的实体数据(在不需要更新其数据时使用),可提长查询性能 + /// + /// + /// + /// + public static ISelect NoTracking(this ISelect select) where T : class + { + return select.TrackToList(null); + } - /// - /// 设置 DbContext 选项设置 - /// - /// - /// - public static void SetDbContextOptions(this IFreeSql that, Action options) { - if (options == null) return; - var cfg = _dicSetDbContextOptions.GetOrAdd(that, t => new DbContextOptions()); - options(cfg); - _dicSetDbContextOptions.AddOrUpdate(that, cfg, (t, o) => cfg); - } - internal static ConcurrentDictionary _dicSetDbContextOptions = new ConcurrentDictionary(); + /// + /// 设置 DbContext 选项设置 + /// + /// + /// + public static void SetDbContextOptions(this IFreeSql that, Action options) + { + if (options == null) return; + var cfg = _dicSetDbContextOptions.GetOrAdd(that, t => new DbContextOptions()); + options(cfg); + _dicSetDbContextOptions.AddOrUpdate(that, cfg, (t, o) => cfg); + } + internal static ConcurrentDictionary _dicSetDbContextOptions = new ConcurrentDictionary(); } \ No newline at end of file diff --git a/FreeSql.DbContext/Repository/ContextSet/RepositoryDbContext.cs b/FreeSql.DbContext/Repository/ContextSet/RepositoryDbContext.cs index ac3dbf7a..643850d2 100644 --- a/FreeSql.DbContext/Repository/ContextSet/RepositoryDbContext.cs +++ b/FreeSql.DbContext/Repository/ContextSet/RepositoryDbContext.cs @@ -3,60 +3,69 @@ using System.Collections.Concurrent; using System.Reflection; using System.Threading.Tasks; -namespace FreeSql { - internal class RepositoryDbContext : DbContext { +namespace FreeSql +{ + internal class RepositoryDbContext : DbContext + { - protected IBaseRepository _repos; - public RepositoryDbContext(IFreeSql orm, IBaseRepository repos) : base() { - _orm = orm; - _repos = repos; - _isUseUnitOfWork = false; - _uowPriv = _repos.UnitOfWork; - } + protected IBaseRepository _repos; + public RepositoryDbContext(IFreeSql orm, IBaseRepository repos) : base() + { + _orm = orm; + _repos = repos; + _isUseUnitOfWork = false; + _uowPriv = _repos.UnitOfWork; + } - static ConcurrentDictionary _dicGetRepositoryDbField = new ConcurrentDictionary(); - static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic)); - public override IDbSet Set(Type entityType) { - if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType]; + static ConcurrentDictionary _dicGetRepositoryDbField = new ConcurrentDictionary(); + static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic)); + public override IDbSet Set(Type entityType) + { + if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType]; - var tb = _orm.CodeFirst.GetTableByEntity(entityType); - if (tb == null) return null; + var tb = _orm.CodeFirst.GetTableByEntity(entityType); + if (tb == null) return null; - object repos = _repos; - if (entityType != _repos.EntityType) { - repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(entityType, typeof(int)), _repos.Orm); - (repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork; - GetRepositoryDbField(entityType).SetValue(repos, this); + object repos = _repos; + if (entityType != _repos.EntityType) + { + repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(entityType, typeof(int)), _repos.Orm); + (repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork; + GetRepositoryDbField(entityType).SetValue(repos, this); - typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EntityType) - .Invoke(null, new object[] { repos, _repos }); - } + typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EntityType) + .Invoke(null, new object[] { repos, _repos }); + } - var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(entityType), repos) as IDbSet; - if (entityType != typeof(object)) _dicSet.Add(entityType, sd); - return sd; - } + var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(entityType), repos) as IDbSet; + if (entityType != typeof(object)) _dicSet.Add(entityType, sd); + return sd; + } - public static void SetRepositoryDataFilter(object repos, BaseRepository baseRepo) where TEntity : class { - var filter = baseRepo.DataFilter as DataFilter; - DataFilterUtil.SetRepositoryDataFilter(repos, fl => { - foreach (var f in filter._filters) - fl.Apply(f.Key, f.Value.Expression); - }); - } + public static void SetRepositoryDataFilter(object repos, BaseRepository baseRepo) where TEntity : class + { + var filter = baseRepo.DataFilter as DataFilter; + DataFilterUtil.SetRepositoryDataFilter(repos, fl => + { + foreach (var f in filter._filters) + fl.Apply(f.Key, f.Value.Expression); + }); + } - public override int SaveChanges() { - ExecCommand(); - var ret = _affrows; - _affrows = 0; - return ret; - } - async public override Task SaveChangesAsync() { - await ExecCommandAsync(); - var ret = _affrows; - _affrows = 0; - return ret; - } - } + public override int SaveChanges() + { + ExecCommand(); + var ret = _affrows; + _affrows = 0; + return ret; + } + async public override Task SaveChangesAsync() + { + await ExecCommandAsync(); + var ret = _affrows; + _affrows = 0; + return ret; + } + } } diff --git a/FreeSql.DbContext/Repository/ContextSet/RepositoryDbSet.cs b/FreeSql.DbContext/Repository/ContextSet/RepositoryDbSet.cs index b50225ed..d88188ba 100644 --- a/FreeSql.DbContext/Repository/ContextSet/RepositoryDbSet.cs +++ b/FreeSql.DbContext/Repository/ContextSet/RepositoryDbSet.cs @@ -3,58 +3,67 @@ using System; using System.Collections.Generic; using System.Linq; -namespace FreeSql { - internal class RepositoryDbSet : DbSet where TEntity : class { +namespace FreeSql +{ + internal class RepositoryDbSet : DbSet where TEntity : class + { - protected BaseRepository _repos; - public RepositoryDbSet(BaseRepository repos) { - _ctx = repos._db; - _fsql = repos.Orm; - _uow = repos.UnitOfWork; - _repos = repos; - } + protected BaseRepository _repos; + public RepositoryDbSet(BaseRepository repos) + { + _ctx = repos._db; + _fsql = repos.Orm; + _uow = repos.UnitOfWork; + _repos = repos; + } - protected override ISelect OrmSelect(object dywhere) { - var select = base.OrmSelect(dywhere); + protected override ISelect OrmSelect(object dywhere) + { + var select = base.OrmSelect(dywhere); - var filters = (_repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); - foreach (var filter in filters) select.Where(filter.Value.Expression); - return select.AsTable(_repos.AsTableSelectInternal); - } - internal ISelect OrmSelectInternal(object dywhere) => OrmSelect(dywhere); - protected override IUpdate OrmUpdate(IEnumerable entitys) { - var update = base.OrmUpdate(entitys); - var filters = (_repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); - foreach (var filter in filters) { - if (entitys != null) - foreach (var entity in entitys) - if (filter.Value.ExpressionDelegate?.Invoke(entity) == false) - throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_fsql.GetEntityString(_entityType, entity)}"); - update.Where(filter.Value.Expression); - } - return update.AsTable(_repos.AsTableInternal); - } - internal IUpdate OrmUpdateInternal(IEnumerable entitys) => OrmUpdate(entitys); - protected override IDelete OrmDelete(object dywhere) { - var delete = base.OrmDelete(dywhere); - var filters = (_repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); - foreach (var filter in filters) delete.Where(filter.Value.Expression); - return delete.AsTable(_repos.AsTableInternal); - } - internal IDelete OrmDeleteInternal(object dywhere) => OrmDelete(dywhere); - protected override IInsert OrmInsert(TEntity entity) => OrmInsert(new[] { entity }); - protected override IInsert OrmInsert(IEnumerable entitys) { - var insert = base.OrmInsert(entitys); - var filters = (_repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); - foreach (var filter in filters) { - if (entitys != null) - foreach (var entity in entitys) - if (filter.Value.ExpressionDelegate?.Invoke(entity) == false) - throw new Exception($"FreeSql.Repository Insert 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},插入的数据不符合 {_fsql.GetEntityString(_entityType, entity)}"); - } - return insert.AsTable(_repos.AsTableInternal); - } - internal IInsert OrmInsertInternal(TEntity entity) => OrmInsert(entity); - internal IInsert OrmInsertInternal(IEnumerable entitys) => OrmInsert(entitys); - } + var filters = (_repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); + foreach (var filter in filters) select.Where(filter.Value.Expression); + return select.AsTable(_repos.AsTableSelectInternal); + } + internal ISelect OrmSelectInternal(object dywhere) => OrmSelect(dywhere); + protected override IUpdate OrmUpdate(IEnumerable entitys) + { + var update = base.OrmUpdate(entitys); + var filters = (_repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); + foreach (var filter in filters) + { + if (entitys != null) + foreach (var entity in entitys) + if (filter.Value.ExpressionDelegate?.Invoke(entity) == false) + throw new Exception($"FreeSql.Repository Update 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},更新的数据不符合 {_fsql.GetEntityString(_entityType, entity)}"); + update.Where(filter.Value.Expression); + } + return update.AsTable(_repos.AsTableInternal); + } + internal IUpdate OrmUpdateInternal(IEnumerable entitys) => OrmUpdate(entitys); + protected override IDelete OrmDelete(object dywhere) + { + var delete = base.OrmDelete(dywhere); + var filters = (_repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); + foreach (var filter in filters) delete.Where(filter.Value.Expression); + return delete.AsTable(_repos.AsTableInternal); + } + internal IDelete OrmDeleteInternal(object dywhere) => OrmDelete(dywhere); + protected override IInsert OrmInsert(TEntity entity) => OrmInsert(new[] { entity }); + protected override IInsert OrmInsert(IEnumerable entitys) + { + var insert = base.OrmInsert(entitys); + var filters = (_repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); + foreach (var filter in filters) + { + if (entitys != null) + foreach (var entity in entitys) + if (filter.Value.ExpressionDelegate?.Invoke(entity) == false) + throw new Exception($"FreeSql.Repository Insert 失败,因为设置了过滤器 {filter.Key}: {filter.Value.Expression},插入的数据不符合 {_fsql.GetEntityString(_entityType, entity)}"); + } + return insert.AsTable(_repos.AsTableInternal); + } + internal IInsert OrmInsertInternal(TEntity entity) => OrmInsert(entity); + internal IInsert OrmInsertInternal(IEnumerable entitys) => OrmInsert(entitys); + } } diff --git a/FreeSql.DbContext/Repository/ContextSet/RepositoryUnitOfWork.cs b/FreeSql.DbContext/Repository/ContextSet/RepositoryUnitOfWork.cs index d36c4887..7166ef2c 100644 --- a/FreeSql.DbContext/Repository/ContextSet/RepositoryUnitOfWork.cs +++ b/FreeSql.DbContext/Repository/ContextSet/RepositoryUnitOfWork.cs @@ -1,57 +1,64 @@ using System; using System.Linq.Expressions; -namespace FreeSql { +namespace FreeSql +{ - public interface IRepositoryUnitOfWork : IUnitOfWork { - /// - /// 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点 - /// - /// - /// - /// 数据过滤 + 验证 - /// - DefaultRepository GetRepository(Expression> filter = null) where TEntity : class; + public interface IRepositoryUnitOfWork : IUnitOfWork + { + /// + /// 在工作单元内创建默认仓库类,工作单元下的仓储操作具有事务特点 + /// + /// + /// + /// 数据过滤 + 验证 + /// + DefaultRepository GetRepository(Expression> filter = null) where TEntity : class; - /// - /// 在工作单元内创建联合主键的仓储类,工作单元下的仓储操作具有事务特点 - /// - /// - /// 数据过滤 + 验证 - /// - BaseRepository GetRepository(Expression> filter = null) where TEntity : class; + /// + /// 在工作单元内创建联合主键的仓储类,工作单元下的仓储操作具有事务特点 + /// + /// + /// 数据过滤 + 验证 + /// + BaseRepository GetRepository(Expression> filter = null) where TEntity : class; - /// - /// 在工作单元内创建仓库类,工作单元下的仓储操作具有事务特点 - /// - /// - /// 数据过滤 + 验证 - /// 分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository - /// - GuidRepository GetGuidRepository(Expression> filter = null, Func asTable = null) where TEntity : class; - } + /// + /// 在工作单元内创建仓库类,工作单元下的仓储操作具有事务特点 + /// + /// + /// 数据过滤 + 验证 + /// 分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository + /// + GuidRepository GetGuidRepository(Expression> filter = null, Func asTable = null) where TEntity : class; + } - class RepositoryUnitOfWork : UnitOfWork, IRepositoryUnitOfWork { + class RepositoryUnitOfWork : UnitOfWork, IRepositoryUnitOfWork + { - public RepositoryUnitOfWork(IFreeSql fsql) : base(fsql) { - } + public RepositoryUnitOfWork(IFreeSql fsql) : base(fsql) + { + } - public GuidRepository GetGuidRepository(Expression> filter = null, Func asTable = null) where TEntity : class { - var repos = new GuidRepository(_fsql, filter, asTable); - repos.UnitOfWork = this; - return repos; - } + public GuidRepository GetGuidRepository(Expression> filter = null, Func asTable = null) where TEntity : class + { + var repos = new GuidRepository(_fsql, filter, asTable); + repos.UnitOfWork = this; + return repos; + } - public DefaultRepository GetRepository(Expression> filter = null) where TEntity : class { - var repos = new DefaultRepository(_fsql, filter); - repos.UnitOfWork = this; - return repos; - } + public DefaultRepository GetRepository(Expression> filter = null) where TEntity : class + { + var repos = new DefaultRepository(_fsql, filter); + repos.UnitOfWork = this; + return repos; + } - public BaseRepository GetRepository(Expression> filter = null) where TEntity : class { - var repos = new DefaultRepository(_fsql, filter); - repos.UnitOfWork = this; - return repos; - } - } + public BaseRepository GetRepository(Expression> filter = null) where TEntity : class + { + var repos = new DefaultRepository(_fsql, filter); + repos.UnitOfWork = this; + return repos; + } + } } diff --git a/FreeSql.DbContext/Repository/DataFilter/DataFilter.cs b/FreeSql.DbContext/Repository/DataFilter/DataFilter.cs index d65a3b0a..b03874bd 100644 --- a/FreeSql.DbContext/Repository/DataFilter/DataFilter.cs +++ b/FreeSql.DbContext/Repository/DataFilter/DataFilter.cs @@ -4,149 +4,178 @@ using System.Collections.Concurrent; using System.Linq.Expressions; using System.Linq; -namespace FreeSql { - public interface IDataFilter : IDisposable where TEntity : class { +namespace FreeSql +{ + public interface IDataFilter : IDisposable where TEntity : class + { - IDataFilter Apply(string filterName, Expression> filterAndValidateExp); + IDataFilter Apply(string filterName, Expression> filterAndValidateExp); - /// - /// 开启过滤器,若使用 using 则使用完后,恢复为原有状态 - /// - /// 过滤器名称 - /// - IDisposable Enable(params string[] filterName); - /// - /// 开启所有过滤器,若使用 using 则使用完后,恢复为原有状态 - /// - /// - IDisposable EnableAll(); + /// + /// 开启过滤器,若使用 using 则使用完后,恢复为原有状态 + /// + /// 过滤器名称 + /// + IDisposable Enable(params string[] filterName); + /// + /// 开启所有过滤器,若使用 using 则使用完后,恢复为原有状态 + /// + /// + IDisposable EnableAll(); - /// - /// 禁用过滤器,若使用 using 则使用完后,恢复为原有状态 - /// - /// - /// - IDisposable Disable(params string[] filterName); - /// - /// 禁用所有过滤器,若使用 using 则使用完后,恢复为原有状态 - /// - /// - IDisposable DisableAll(); + /// + /// 禁用过滤器,若使用 using 则使用完后,恢复为原有状态 + /// + /// + /// + IDisposable Disable(params string[] filterName); + /// + /// 禁用所有过滤器,若使用 using 则使用完后,恢复为原有状态 + /// + /// + IDisposable DisableAll(); - bool IsEnabled(string filterName); - } + bool IsEnabled(string filterName); + } - internal class DataFilter : IDataFilter where TEntity : class { + internal class DataFilter : IDataFilter where TEntity : class + { - internal class FilterItem { - public Expression> Expression { get; set; } - Func _expressionDelegate; - public Func ExpressionDelegate => _expressionDelegate ?? (_expressionDelegate = Expression?.Compile()); - public bool IsEnabled { get; set; } - } + internal class FilterItem + { + public Expression> Expression { get; set; } + Func _expressionDelegate; + public Func ExpressionDelegate => _expressionDelegate ?? (_expressionDelegate = Expression?.Compile()); + public bool IsEnabled { get; set; } + } - internal ConcurrentDictionary _filters = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - public IDataFilter Apply(string filterName, Expression> filterAndValidateExp) { + internal ConcurrentDictionary _filters = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + public IDataFilter Apply(string filterName, Expression> filterAndValidateExp) + { - if (filterName == null) - throw new ArgumentNullException(nameof(filterName)); - if (filterAndValidateExp == null) return this; + if (filterName == null) + throw new ArgumentNullException(nameof(filterName)); + if (filterAndValidateExp == null) return this; - var filterItem = new FilterItem { Expression = filterAndValidateExp, IsEnabled = true }; - _filters.AddOrUpdate(filterName, filterItem, (k, v) => filterItem); - return this; - } + var filterItem = new FilterItem { Expression = filterAndValidateExp, IsEnabled = true }; + _filters.AddOrUpdate(filterName, filterItem, (k, v) => filterItem); + return this; + } - public IDisposable Disable(params string[] filterName) { - if (filterName == null || filterName.Any() == false) return new UsingAny(() => { }); + public IDisposable Disable(params string[] filterName) + { + if (filterName == null || filterName.Any() == false) return new UsingAny(() => { }); - List restore = new List(); - foreach (var name in filterName) { - if (_filters.TryGetValue(name, out var tryfi)) { - if (tryfi.IsEnabled) { - restore.Add(name); - tryfi.IsEnabled = false; - } - } - } - return new UsingAny(() => this.Enable(restore.ToArray())); - } - public IDisposable DisableAll() { - List restore = new List(); - foreach (var val in _filters) { - if (val.Value.IsEnabled) { - restore.Add(val.Key); - val.Value.IsEnabled = false; - } - } - return new UsingAny(() => this.Enable(restore.ToArray())); - } - class UsingAny : IDisposable { - Action _ondis; - public UsingAny(Action ondis) { - _ondis = ondis; - } - public void Dispose() { - _ondis?.Invoke(); - } - } + List restore = new List(); + foreach (var name in filterName) + { + if (_filters.TryGetValue(name, out var tryfi)) + { + if (tryfi.IsEnabled) + { + restore.Add(name); + tryfi.IsEnabled = false; + } + } + } + return new UsingAny(() => this.Enable(restore.ToArray())); + } + public IDisposable DisableAll() + { + List restore = new List(); + foreach (var val in _filters) + { + if (val.Value.IsEnabled) + { + restore.Add(val.Key); + val.Value.IsEnabled = false; + } + } + return new UsingAny(() => this.Enable(restore.ToArray())); + } + class UsingAny : IDisposable + { + Action _ondis; + public UsingAny(Action ondis) + { + _ondis = ondis; + } + public void Dispose() + { + _ondis?.Invoke(); + } + } - public IDisposable Enable(params string[] filterName) { - if (filterName == null || filterName.Any() == false) return new UsingAny(() => { }); + public IDisposable Enable(params string[] filterName) + { + if (filterName == null || filterName.Any() == false) return new UsingAny(() => { }); - List restore = new List(); - foreach (var name in filterName) { - if (_filters.TryGetValue(name, out var tryfi)) { - if (tryfi.IsEnabled == false) { - restore.Add(name); - tryfi.IsEnabled = true; - } - } - } - return new UsingAny(() => this.Disable(restore.ToArray())); - } - public IDisposable EnableAll() { - List restore = new List(); - foreach (var val in _filters) { - if (val.Value.IsEnabled == false) { - restore.Add(val.Key); - val.Value.IsEnabled = true; - } - } - return new UsingAny(() => this.Disable(restore.ToArray())); - } + List restore = new List(); + foreach (var name in filterName) + { + if (_filters.TryGetValue(name, out var tryfi)) + { + if (tryfi.IsEnabled == false) + { + restore.Add(name); + tryfi.IsEnabled = true; + } + } + } + return new UsingAny(() => this.Disable(restore.ToArray())); + } + public IDisposable EnableAll() + { + List restore = new List(); + foreach (var val in _filters) + { + if (val.Value.IsEnabled == false) + { + restore.Add(val.Key); + val.Value.IsEnabled = true; + } + } + return new UsingAny(() => this.Disable(restore.ToArray())); + } - public bool IsEnabled(string filterName) { - if (filterName == null) return false; - return _filters.TryGetValue(filterName, out var tryfi) ? tryfi.IsEnabled : false; - } + public bool IsEnabled(string filterName) + { + if (filterName == null) return false; + return _filters.TryGetValue(filterName, out var tryfi) ? tryfi.IsEnabled : false; + } - ~DataFilter() { - this.Dispose(); - } - public void Dispose() { - _filters.Clear(); - } - } + ~DataFilter() + { + this.Dispose(); + } + public void Dispose() + { + _filters.Clear(); + } + } - public class FluentDataFilter : IDisposable { + public class FluentDataFilter : IDisposable + { - internal List<(Type type, string name, LambdaExpression exp)> _filters = new List<(Type type, string name, LambdaExpression exp)>(); + internal List<(Type type, string name, LambdaExpression exp)> _filters = new List<(Type type, string name, LambdaExpression exp)>(); - public FluentDataFilter Apply(string filterName, Expression> filterAndValidateExp) where TEntity : class { - if (filterName == null) - throw new ArgumentNullException(nameof(filterName)); - if (filterAndValidateExp == null) return this; + public FluentDataFilter Apply(string filterName, Expression> filterAndValidateExp) where TEntity : class + { + if (filterName == null) + throw new ArgumentNullException(nameof(filterName)); + if (filterAndValidateExp == null) return this; - _filters.Add((typeof(TEntity), filterName, filterAndValidateExp)); - return this; - } + _filters.Add((typeof(TEntity), filterName, filterAndValidateExp)); + return this; + } - ~FluentDataFilter() { - this.Dispose(); - } - public void Dispose() { - _filters.Clear(); - } - } + ~FluentDataFilter() + { + this.Dispose(); + } + public void Dispose() + { + _filters.Clear(); + } + } } diff --git a/FreeSql.DbContext/Repository/DataFilter/DataFilterUtil.cs b/FreeSql.DbContext/Repository/DataFilter/DataFilterUtil.cs index b94905b4..f626bc3a 100644 --- a/FreeSql.DbContext/Repository/DataFilter/DataFilterUtil.cs +++ b/FreeSql.DbContext/Repository/DataFilter/DataFilterUtil.cs @@ -5,85 +5,100 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; -namespace FreeSql { +namespace FreeSql +{ - internal class DataFilterUtil { + internal class DataFilterUtil + { - internal static Action _globalDataFilter; + internal static Action _globalDataFilter; - static ConcurrentDictionary _dicSetRepositoryDataFilterApplyDataFilterFunc = new ConcurrentDictionary(); - static ConcurrentDictionary> _dicSetRepositoryDataFilterConvertFilterNotExists = new ConcurrentDictionary>(); - internal static void SetRepositoryDataFilter(object repos, Action scopedDataFilter) { - if (scopedDataFilter != null) { - SetRepositoryDataFilter(repos, null); - } - if (scopedDataFilter == null) { - scopedDataFilter = _globalDataFilter; - } - if (scopedDataFilter == null) return; - using (var globalFilter = new FluentDataFilter()) { - scopedDataFilter(globalFilter); + static ConcurrentDictionary _dicSetRepositoryDataFilterApplyDataFilterFunc = new ConcurrentDictionary(); + static ConcurrentDictionary> _dicSetRepositoryDataFilterConvertFilterNotExists = new ConcurrentDictionary>(); + internal static void SetRepositoryDataFilter(object repos, Action scopedDataFilter) + { + if (scopedDataFilter != null) + { + SetRepositoryDataFilter(repos, null); + } + if (scopedDataFilter == null) + { + scopedDataFilter = _globalDataFilter; + } + if (scopedDataFilter == null) return; + using (var globalFilter = new FluentDataFilter()) + { + scopedDataFilter(globalFilter); - var type = repos.GetType(); - Type entityType = (repos as IBaseRepository).EntityType; - if (entityType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository"); + var type = repos.GetType(); + Type entityType = (repos as IBaseRepository).EntityType; + if (entityType == null) throw new Exception("FreeSql.Repository 设置过滤器失败,原因是对象不属于 IRepository"); - var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary()); - var newFilter = new Dictionary(); - foreach (var gf in globalFilter._filters) { - if (notExists.ContainsKey(gf.name)) continue; + var notExists = _dicSetRepositoryDataFilterConvertFilterNotExists.GetOrAdd(type, t => new ConcurrentDictionary()); + var newFilter = new Dictionary(); + foreach (var gf in globalFilter._filters) + { + if (notExists.ContainsKey(gf.name)) continue; - LambdaExpression newExp = null; - var filterParameter1 = Expression.Parameter(entityType, gf.exp.Parameters[0].Name); - try { - newExp = Expression.Lambda( - typeof(Func<,>).MakeGenericType(entityType, typeof(bool)), - new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1), - filterParameter1 - ); - } catch { - notExists.TryAdd(gf.name, true); //防止第二次错误 - continue; - } - newFilter.Add(gf.name, newExp); - } - if (newFilter.Any() == false) return; + LambdaExpression newExp = null; + var filterParameter1 = Expression.Parameter(entityType, gf.exp.Parameters[0].Name); + try + { + newExp = Expression.Lambda( + typeof(Func<,>).MakeGenericType(entityType, typeof(bool)), + new ReplaceVisitor().Modify(gf.exp.Body, filterParameter1), + filterParameter1 + ); + } + catch + { + notExists.TryAdd(gf.name, true); //防止第二次错误 + continue; + } + newFilter.Add(gf.name, newExp); + } + if (newFilter.Any() == false) return; - var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => { - var reposParameter = Expression.Parameter(type); - var nameParameter = Expression.Parameter(typeof(string)); - var expressionParameter = Expression.Parameter( - typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(entityType, typeof(bool))) - ); - return Expression.Lambda( - Expression.Block( - Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter) - ), - new[] { - reposParameter, nameParameter, expressionParameter - } - ).Compile(); - }); - foreach (var nf in newFilter) { - del.DynamicInvoke(repos, nf.Key, nf.Value); - } - newFilter.Clear(); - } - } - } + var del = _dicSetRepositoryDataFilterApplyDataFilterFunc.GetOrAdd(type, t => + { + var reposParameter = Expression.Parameter(type); + var nameParameter = Expression.Parameter(typeof(string)); + var expressionParameter = Expression.Parameter( + typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(entityType, typeof(bool))) + ); + return Expression.Lambda( + Expression.Block( + Expression.Call(reposParameter, type.GetMethod("ApplyDataFilter", BindingFlags.Instance | BindingFlags.NonPublic), nameParameter, expressionParameter) + ), + new[] { + reposParameter, nameParameter, expressionParameter + } + ).Compile(); + }); + foreach (var nf in newFilter) + { + del.DynamicInvoke(repos, nf.Key, nf.Value); + } + newFilter.Clear(); + } + } + } - class ReplaceVisitor : ExpressionVisitor { - private ParameterExpression parameter; + class ReplaceVisitor : ExpressionVisitor + { + private ParameterExpression parameter; - public Expression Modify(Expression expression, ParameterExpression parameter) { - this.parameter = parameter; - return Visit(expression); - } + public Expression Modify(Expression expression, ParameterExpression parameter) + { + this.parameter = parameter; + return Visit(expression); + } - protected override Expression VisitMember(MemberExpression node) { - if (node.Expression?.NodeType == ExpressionType.Parameter) - return Expression.Property(parameter, node.Member.Name); - return base.VisitMember(node); - } - } + protected override Expression VisitMember(MemberExpression node) + { + if (node.Expression?.NodeType == ExpressionType.Parameter) + return Expression.Property(parameter, node.Member.Name); + return base.VisitMember(node); + } + } } diff --git a/FreeSql.DbContext/Repository/Extenssions/DependencyInjection.cs b/FreeSql.DbContext/Repository/Extenssions/DependencyInjection.cs index 9265774d..f37848a8 100644 --- a/FreeSql.DbContext/Repository/Extenssions/DependencyInjection.cs +++ b/FreeSql.DbContext/Repository/Extenssions/DependencyInjection.cs @@ -5,35 +5,41 @@ using System.Reflection; using System.Linq; using Microsoft.Extensions.DependencyInjection; -namespace FreeSql { - public static class FreeSqlRepositoryDependencyInjection { +namespace FreeSql +{ + public static class FreeSqlRepositoryDependencyInjection + { - public static IServiceCollection AddFreeRepository(this IServiceCollection services, Action globalDataFilter = null, params Assembly[] assemblies) { + public static IServiceCollection AddFreeRepository(this IServiceCollection services, Action globalDataFilter = null, params Assembly[] assemblies) + { - DataFilterUtil._globalDataFilter = globalDataFilter; + DataFilterUtil._globalDataFilter = globalDataFilter; - services.AddScoped(typeof(IReadOnlyRepository<>), typeof(GuidRepository<>)); - services.AddScoped(typeof(IBasicRepository<>), typeof(GuidRepository<>)); - services.AddScoped(typeof(BaseRepository<>), typeof(GuidRepository<>)); - services.AddScoped(typeof(GuidRepository<>)); + services.AddScoped(typeof(IReadOnlyRepository<>), typeof(GuidRepository<>)); + services.AddScoped(typeof(IBasicRepository<>), typeof(GuidRepository<>)); + services.AddScoped(typeof(BaseRepository<>), typeof(GuidRepository<>)); + services.AddScoped(typeof(GuidRepository<>)); - services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(DefaultRepository<,>)); - services.AddScoped(typeof(IBasicRepository<,>), typeof(DefaultRepository<,>)); - services.AddScoped(typeof(BaseRepository<,>), typeof(DefaultRepository<,>)); - services.AddScoped(typeof(DefaultRepository<,>)); + services.AddScoped(typeof(IReadOnlyRepository<,>), typeof(DefaultRepository<,>)); + services.AddScoped(typeof(IBasicRepository<,>), typeof(DefaultRepository<,>)); + services.AddScoped(typeof(BaseRepository<,>), typeof(DefaultRepository<,>)); + services.AddScoped(typeof(DefaultRepository<,>)); - if (assemblies?.Any() == true) { - foreach(var asse in assemblies) { - foreach (var repos in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(IBaseRepository).IsAssignableFrom(a))) { + if (assemblies?.Any() == true) + { + foreach (var asse in assemblies) + { + foreach (var repos in asse.GetTypes().Where(a => a.IsAbstract == false && typeof(IBaseRepository).IsAssignableFrom(a))) + { - services.AddScoped(repos); - } - } - } + services.AddScoped(repos); + } + } + } - return services; - } - } + return services; + } + } } #endif \ No newline at end of file diff --git a/FreeSql.DbContext/Repository/Extenssions/FreeSqlRepositoryExtenssions.cs b/FreeSql.DbContext/Repository/Extenssions/FreeSqlRepositoryExtenssions.cs index 5c4fedd3..e34af18e 100644 --- a/FreeSql.DbContext/Repository/Extenssions/FreeSqlRepositoryExtenssions.cs +++ b/FreeSql.DbContext/Repository/Extenssions/FreeSqlRepositoryExtenssions.cs @@ -3,63 +3,69 @@ using System; using System.Linq.Expressions; using System.Linq; -public static class FreeSqlRepositoryExtenssions { +public static class FreeSqlRepositoryExtenssions +{ - /// - /// 返回默认仓库类 - /// - /// - /// - /// - /// 数据过滤 + 验证 - /// - public static DefaultRepository GetRepository(this IFreeSql that, Expression> filter = null) where TEntity : class { - return new DefaultRepository(that, filter); - } + /// + /// 返回默认仓库类 + /// + /// + /// + /// + /// 数据过滤 + 验证 + /// + public static DefaultRepository GetRepository(this IFreeSql that, Expression> filter = null) where TEntity : class + { + return new DefaultRepository(that, filter); + } - /// - /// 返回默认仓库类,适用联合主键的仓储类 - /// - /// - /// - /// 数据过滤 + 验证 - /// - public static BaseRepository GetRepository(this IFreeSql that, Expression> filter = null) where TEntity : class { - return new DefaultRepository(that, filter); - } + /// + /// 返回默认仓库类,适用联合主键的仓储类 + /// + /// + /// + /// 数据过滤 + 验证 + /// + public static BaseRepository GetRepository(this IFreeSql that, Expression> filter = null) where TEntity : class + { + return new DefaultRepository(that, filter); + } - /// - /// 返回仓库类 - /// - /// - /// - /// 数据过滤 + 验证 - /// 分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository - /// - public static GuidRepository GetGuidRepository(this IFreeSql that, Expression> filter = null, Func asTable = null) where TEntity : class { - return new GuidRepository(that, filter, asTable); - } + /// + /// 返回仓库类 + /// + /// + /// + /// 数据过滤 + 验证 + /// 分表规则,参数:旧表名;返回:新表名 https://github.com/2881099/FreeSql/wiki/Repository + /// + public static GuidRepository GetGuidRepository(this IFreeSql that, Expression> filter = null, Func asTable = null) where TEntity : class + { + return new GuidRepository(that, filter, asTable); + } - /// - /// 合并两个仓储的设置(过滤+分表),以便查询 - /// - /// - /// - /// - /// - /// - public static ISelect FromRepository(this ISelect that, BaseRepository repos) where TEntity : class where T2 : class { - var filters = (repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); - foreach (var filter in filters) that.Where(filter.Value.Expression); - return that.AsTable(repos.AsTableSelectInternal); - } + /// + /// 合并两个仓储的设置(过滤+分表),以便查询 + /// + /// + /// + /// + /// + /// + public static ISelect FromRepository(this ISelect that, BaseRepository repos) where TEntity : class where T2 : class + { + var filters = (repos.DataFilter as DataFilter)._filters.Where(a => a.Value.IsEnabled == true); + foreach (var filter in filters) that.Where(filter.Value.Expression); + return that.AsTable(repos.AsTableSelectInternal); + } - /// - /// 创建基于仓储功能的工作单元,务必使用 using 包含使用 - /// - /// - /// - public static IRepositoryUnitOfWork CreateUnitOfWork(this IFreeSql that) { - return new RepositoryUnitOfWork(that); - } + /// + /// 创建基于仓储功能的工作单元,务必使用 using 包含使用 + /// + /// + /// + public static IRepositoryUnitOfWork CreateUnitOfWork(this IFreeSql that) + { + return new RepositoryUnitOfWork(that); + } } \ No newline at end of file diff --git a/FreeSql.DbContext/Repository/Repository/BaseRepository.cs b/FreeSql.DbContext/Repository/Repository/BaseRepository.cs index 5ecbd52d..78021b76 100644 --- a/FreeSql.DbContext/Repository/Repository/BaseRepository.cs +++ b/FreeSql.DbContext/Repository/Repository/BaseRepository.cs @@ -4,157 +4,185 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public abstract class BaseRepository : IBaseRepository - where TEntity : class { +namespace FreeSql +{ + public abstract class BaseRepository : IBaseRepository + where TEntity : class + { - internal RepositoryDbContext _dbPriv; - internal RepositoryDbContext _db => _dbPriv ?? (_dbPriv = new RepositoryDbContext(Orm, this)); - internal RepositoryDbSet _dbsetPriv; - internal RepositoryDbSet _dbset => _dbsetPriv ?? (_dbsetPriv = _db.Set() as RepositoryDbSet); - public IDataFilter DataFilter { get; } = new DataFilter(); - Func _asTableVal; - protected Func AsTable { - get => _asTableVal; - set { - _asTableVal = value; - AsTableSelect = value == null ? null : new Func((a, b) => a == EntityType ? value(b) : null); - } - } - internal Func AsTableInternal => AsTable; - protected Func AsTableSelect { get; private set; } - internal Func AsTableSelectInternal => AsTableSelect; + internal RepositoryDbContext _dbPriv; + internal RepositoryDbContext _db => _dbPriv ?? (_dbPriv = new RepositoryDbContext(Orm, this)); + internal RepositoryDbSet _dbsetPriv; + internal RepositoryDbSet _dbset => _dbsetPriv ?? (_dbsetPriv = _db.Set() as RepositoryDbSet); + public IDataFilter DataFilter { get; } = new DataFilter(); + Func _asTableVal; + protected Func AsTable + { + get => _asTableVal; + set + { + _asTableVal = value; + AsTableSelect = value == null ? null : new Func((a, b) => a == EntityType ? value(b) : null); + } + } + internal Func AsTableInternal => AsTable; + protected Func AsTableSelect { get; private set; } + internal Func AsTableSelectInternal => AsTableSelect; - protected void ApplyDataFilter(string name, Expression> exp) => DataFilter.Apply(name, exp); + protected void ApplyDataFilter(string name, Expression> exp) => DataFilter.Apply(name, exp); - protected BaseRepository(IFreeSql fsql, Expression> filter, Func asTable = null) { - Orm = fsql; - DataFilterUtil.SetRepositoryDataFilter(this, null); - DataFilter.Apply("", filter); - AsTable = asTable; - } + protected BaseRepository(IFreeSql fsql, Expression> filter, Func asTable = null) + { + Orm = fsql; + DataFilterUtil.SetRepositoryDataFilter(this, null); + DataFilter.Apply("", filter); + AsTable = asTable; + } - ~BaseRepository() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - try { - _dbsetPriv?.Dispose(); - _dbPriv?.Dispose(); - this.DataFilter.Dispose(); - } finally { - _isdisposed = true; - GC.SuppressFinalize(this); - } - } - public Type EntityType => _dbsetPriv?.EntityType ?? typeof(TEntity); - public void AsType(Type entityType) => _dbset.AsType(entityType); + ~BaseRepository() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + try + { + _dbsetPriv?.Dispose(); + _dbPriv?.Dispose(); + this.DataFilter.Dispose(); + } + finally + { + _isdisposed = true; + GC.SuppressFinalize(this); + } + } + public Type EntityType => _dbsetPriv?.EntityType ?? typeof(TEntity); + public void AsType(Type entityType) => _dbset.AsType(entityType); - public IFreeSql Orm { get; private set; } - public IUnitOfWork UnitOfWork { get; set; } - public IUpdate UpdateDiy => _dbset.OrmUpdateInternal(null); + public IFreeSql Orm { get; private set; } + public IUnitOfWork UnitOfWork { get; set; } + public IUpdate UpdateDiy => _dbset.OrmUpdateInternal(null); - public ISelect Select => _dbset.OrmSelectInternal(null); - public ISelect Where(Expression> exp) => _dbset.OrmSelectInternal(null).Where(exp); - public ISelect WhereIf(bool condition, Expression> exp) => _dbset.OrmSelectInternal(null).WhereIf(condition, exp); + public ISelect Select => _dbset.OrmSelectInternal(null); + public ISelect Where(Expression> exp) => _dbset.OrmSelectInternal(null).Where(exp); + public ISelect WhereIf(bool condition, Expression> exp) => _dbset.OrmSelectInternal(null).WhereIf(condition, exp); - public int Delete(Expression> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrows(); - public Task DeleteAsync(Expression> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrowsAsync(); + public int Delete(Expression> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrows(); + public Task DeleteAsync(Expression> predicate) => _dbset.OrmDeleteInternal(null).Where(predicate).ExecuteAffrowsAsync(); - public int Delete(TEntity entity) { - _dbset.Remove(entity); - return _db.SaveChanges(); - } - public Task DeleteAsync(TEntity entity) { - _dbset.Remove(entity); - return _db.SaveChangesAsync(); - } - public int Delete(IEnumerable entitys) { - _dbset.RemoveRange(entitys); - return _db.SaveChanges(); - } - public Task DeleteAsync(IEnumerable entitys) { - _dbset.RemoveRange(entitys); - return _db.SaveChangesAsync(); - } + public int Delete(TEntity entity) + { + _dbset.Remove(entity); + return _db.SaveChanges(); + } + public Task DeleteAsync(TEntity entity) + { + _dbset.Remove(entity); + return _db.SaveChangesAsync(); + } + public int Delete(IEnumerable entitys) + { + _dbset.RemoveRange(entitys); + return _db.SaveChanges(); + } + public Task DeleteAsync(IEnumerable entitys) + { + _dbset.RemoveRange(entitys); + return _db.SaveChangesAsync(); + } - public virtual TEntity Insert(TEntity entity) { - _dbset.Add(entity); - _db.SaveChanges(); - return entity; - } - async public virtual Task InsertAsync(TEntity entity) { - await _dbset.AddAsync(entity); - _db.SaveChanges(); - return entity; - } - public virtual List Insert(IEnumerable entitys) { - _dbset.AddRange(entitys); - _db.SaveChanges(); - return entitys.ToList(); - } - async public virtual Task> InsertAsync(IEnumerable entitys) { - await _dbset.AddRangeAsync(entitys); - await _db.SaveChangesAsync(); - return entitys.ToList(); - } + public virtual TEntity Insert(TEntity entity) + { + _dbset.Add(entity); + _db.SaveChanges(); + return entity; + } + async public virtual Task InsertAsync(TEntity entity) + { + await _dbset.AddAsync(entity); + _db.SaveChanges(); + return entity; + } + public virtual List Insert(IEnumerable entitys) + { + _dbset.AddRange(entitys); + _db.SaveChanges(); + return entitys.ToList(); + } + async public virtual Task> InsertAsync(IEnumerable entitys) + { + await _dbset.AddRangeAsync(entitys); + await _db.SaveChangesAsync(); + return entitys.ToList(); + } - public int Update(TEntity entity) { - _dbset.Update(entity); - return _db.SaveChanges(); - } - public Task UpdateAsync(TEntity entity) { - _dbset.Update(entity); - return _db.SaveChangesAsync(); - } - public int Update(IEnumerable entitys) { - _dbset.UpdateRange(entitys); - return _db.SaveChanges(); - } - public Task UpdateAsync(IEnumerable entitys) { - _dbset.UpdateRange(entitys); - return _db.SaveChangesAsync(); - } + public int Update(TEntity entity) + { + _dbset.Update(entity); + return _db.SaveChanges(); + } + public Task UpdateAsync(TEntity entity) + { + _dbset.Update(entity); + return _db.SaveChangesAsync(); + } + public int Update(IEnumerable entitys) + { + _dbset.UpdateRange(entitys); + return _db.SaveChanges(); + } + public Task UpdateAsync(IEnumerable entitys) + { + _dbset.UpdateRange(entitys); + return _db.SaveChangesAsync(); + } - public void Attach(TEntity data) => _db.Attach(data); - public void Attach(IEnumerable data) => _db.AttachRange(data); - public void FlushState() => _dbset.FlushState(); + public void Attach(TEntity data) => _db.Attach(data); + public void Attach(IEnumerable data) => _db.AttachRange(data); + public void FlushState() => _dbset.FlushState(); - public TEntity InsertOrUpdate(TEntity entity) { - _dbset.AddOrUpdate(entity); - _db.SaveChanges(); - return entity; - } - async public Task InsertOrUpdateAsync(TEntity entity) { - await _dbset.AddOrUpdateAsync(entity); - _db.SaveChanges(); - return entity; - } - } + public TEntity InsertOrUpdate(TEntity entity) + { + _dbset.AddOrUpdate(entity); + _db.SaveChanges(); + return entity; + } + async public Task InsertOrUpdateAsync(TEntity entity) + { + await _dbset.AddOrUpdateAsync(entity); + _db.SaveChanges(); + return entity; + } + } - public abstract class BaseRepository : BaseRepository, IBaseRepository - where TEntity : class { + public abstract class BaseRepository : BaseRepository, IBaseRepository + where TEntity : class + { - public BaseRepository(IFreeSql fsql, Expression> filter, Func asTable = null) : base(fsql, filter, asTable) { - } + public BaseRepository(IFreeSql fsql, Expression> filter, Func asTable = null) : base(fsql, filter, asTable) + { + } - public int Delete(TKey id) { - var stateKey = string.Concat(id); - _dbset._statesInternal.TryRemove(stateKey, out var trystate); - return _dbset.OrmDeleteInternal(id).ExecuteAffrows(); - } - public Task DeleteAsync(TKey id) { - var stateKey = string.Concat(id); - _dbset._statesInternal.TryRemove(stateKey, out var trystate); - return _dbset.OrmDeleteInternal(id).ExecuteAffrowsAsync(); - } + public int Delete(TKey id) + { + var stateKey = string.Concat(id); + _dbset._statesInternal.TryRemove(stateKey, out var trystate); + return _dbset.OrmDeleteInternal(id).ExecuteAffrows(); + } + public Task DeleteAsync(TKey id) + { + var stateKey = string.Concat(id); + _dbset._statesInternal.TryRemove(stateKey, out var trystate); + return _dbset.OrmDeleteInternal(id).ExecuteAffrowsAsync(); + } - public TEntity Find(TKey id) => _dbset.OrmSelectInternal(id).ToOne(); - public Task FindAsync(TKey id) => _dbset.OrmSelectInternal(id).ToOneAsync(); + public TEntity Find(TKey id) => _dbset.OrmSelectInternal(id).ToOne(); + public Task FindAsync(TKey id) => _dbset.OrmSelectInternal(id).ToOneAsync(); - public TEntity Get(TKey id) => Find(id); - public Task GetAsync(TKey id) => FindAsync(id); - } + public TEntity Get(TKey id) => Find(id); + public Task GetAsync(TKey id) => FindAsync(id); + } } diff --git a/FreeSql.DbContext/Repository/Repository/DefaultRepository.cs b/FreeSql.DbContext/Repository/Repository/DefaultRepository.cs index 8a711e2f..a1f69e07 100644 --- a/FreeSql.DbContext/Repository/Repository/DefaultRepository.cs +++ b/FreeSql.DbContext/Repository/Repository/DefaultRepository.cs @@ -1,16 +1,20 @@ using System; using System.Linq.Expressions; -namespace FreeSql { - public class DefaultRepository : - BaseRepository - where TEntity : class { +namespace FreeSql +{ + public class DefaultRepository : + BaseRepository + where TEntity : class + { - public DefaultRepository(IFreeSql fsql) : base(fsql, null, null) { + public DefaultRepository(IFreeSql fsql) : base(fsql, null, null) + { - } + } - public DefaultRepository(IFreeSql fsql, Expression> filter) : base(fsql, filter, null) { - } - } + public DefaultRepository(IFreeSql fsql, Expression> filter) : base(fsql, filter, null) + { + } + } } diff --git a/FreeSql.DbContext/Repository/Repository/GuidRepository.cs b/FreeSql.DbContext/Repository/Repository/GuidRepository.cs index f7eba195..1025f961 100644 --- a/FreeSql.DbContext/Repository/Repository/GuidRepository.cs +++ b/FreeSql.DbContext/Repository/Repository/GuidRepository.cs @@ -1,15 +1,19 @@ using System; using System.Linq.Expressions; -namespace FreeSql { - public class GuidRepository : - BaseRepository - where TEntity : class { +namespace FreeSql +{ + public class GuidRepository : + BaseRepository + where TEntity : class + { - public GuidRepository(IFreeSql fsql) : this(fsql, null, null) { + public GuidRepository(IFreeSql fsql) : this(fsql, null, null) + { - } - public GuidRepository(IFreeSql fsql, Expression> filter, Func asTable) : base(fsql, filter, asTable) { - } - } + } + public GuidRepository(IFreeSql fsql, Expression> filter, Func asTable) : base(fsql, filter, asTable) + { + } + } } diff --git a/FreeSql.DbContext/Repository/Repository/IBaseRepository.cs b/FreeSql.DbContext/Repository/Repository/IBaseRepository.cs index f1919f29..432697d8 100644 --- a/FreeSql.DbContext/Repository/Repository/IBaseRepository.cs +++ b/FreeSql.DbContext/Repository/Repository/IBaseRepository.cs @@ -2,29 +2,33 @@ using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { +namespace FreeSql +{ - public interface IBaseRepository : IDisposable { - Type EntityType { get; } - IUnitOfWork UnitOfWork { get; set; } - IFreeSql Orm { get; } + public interface IBaseRepository : IDisposable + { + Type EntityType { get; } + IUnitOfWork UnitOfWork { get; set; } + IFreeSql Orm { get; } - /// - /// 动态Type,在使用 Repository<object> 后使用本方法,指定实体类型 - /// - /// - /// - void AsType(Type entityType); - } + /// + /// 动态Type,在使用 Repository<object> 后使用本方法,指定实体类型 + /// + /// + /// + void AsType(Type entityType); + } - public interface IBaseRepository : IReadOnlyRepository, IBasicRepository - where TEntity : class { - int Delete(Expression> predicate); + public interface IBaseRepository : IReadOnlyRepository, IBasicRepository + where TEntity : class + { + int Delete(Expression> predicate); - Task DeleteAsync(Expression> predicate); - } + Task DeleteAsync(Expression> predicate); + } - public interface IBaseRepository : IBaseRepository, IReadOnlyRepository, IBasicRepository - where TEntity : class { - } + public interface IBaseRepository : IBaseRepository, IReadOnlyRepository, IBasicRepository + where TEntity : class + { + } } \ No newline at end of file diff --git a/FreeSql.DbContext/Repository/Repository/IBasicRepository.cs b/FreeSql.DbContext/Repository/Repository/IBasicRepository.cs index 33d79ec6..21aecb89 100644 --- a/FreeSql.DbContext/Repository/Repository/IBasicRepository.cs +++ b/FreeSql.DbContext/Repository/Repository/IBasicRepository.cs @@ -1,45 +1,48 @@ using System.Collections.Generic; using System.Threading.Tasks; -namespace FreeSql { - public interface IBasicRepository : IReadOnlyRepository - where TEntity : class { - TEntity Insert(TEntity entity); - List Insert(IEnumerable entitys); - Task InsertAsync(TEntity entity); - Task> InsertAsync(IEnumerable entitys); +namespace FreeSql +{ + public interface IBasicRepository : IReadOnlyRepository + where TEntity : class + { + TEntity Insert(TEntity entity); + List Insert(IEnumerable entitys); + Task InsertAsync(TEntity entity); + Task> InsertAsync(IEnumerable entitys); - /// - /// 清空状态数据 - /// - void FlushState(); - /// - /// 附加实体,可用于不查询就更新或删除 - /// - /// - void Attach(TEntity entity); - void Attach(IEnumerable entity); - int Update(TEntity entity); - int Update(IEnumerable entitys); - Task UpdateAsync(TEntity entity); - Task UpdateAsync(IEnumerable entitys); + /// + /// 清空状态数据 + /// + void FlushState(); + /// + /// 附加实体,可用于不查询就更新或删除 + /// + /// + void Attach(TEntity entity); + void Attach(IEnumerable entity); + int Update(TEntity entity); + int Update(IEnumerable entitys); + Task UpdateAsync(TEntity entity); + Task UpdateAsync(IEnumerable entitys); - TEntity InsertOrUpdate(TEntity entity); - Task InsertOrUpdateAsync(TEntity entity); + TEntity InsertOrUpdate(TEntity entity); + Task InsertOrUpdateAsync(TEntity entity); - IUpdate UpdateDiy { get; } + IUpdate UpdateDiy { get; } - int Delete(TEntity entity); - int Delete(IEnumerable entitys); - Task DeleteAsync(TEntity entity); - Task DeleteAsync(IEnumerable entitys); - } + int Delete(TEntity entity); + int Delete(IEnumerable entitys); + Task DeleteAsync(TEntity entity); + Task DeleteAsync(IEnumerable entitys); + } - public interface IBasicRepository : IBasicRepository, IReadOnlyRepository - where TEntity : class { - int Delete(TKey id); + public interface IBasicRepository : IBasicRepository, IReadOnlyRepository + where TEntity : class + { + int Delete(TKey id); - Task DeleteAsync(TKey id); - } + Task DeleteAsync(TKey id); + } } diff --git a/FreeSql.DbContext/Repository/Repository/IReadOnlyRepository.cs b/FreeSql.DbContext/Repository/Repository/IReadOnlyRepository.cs index 8b2f47ee..76728a9c 100644 --- a/FreeSql.DbContext/Repository/Repository/IReadOnlyRepository.cs +++ b/FreeSql.DbContext/Repository/Repository/IReadOnlyRepository.cs @@ -2,26 +2,29 @@ using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface IReadOnlyRepository : IBaseRepository - where TEntity : class { +namespace FreeSql +{ + public interface IReadOnlyRepository : IBaseRepository + where TEntity : class + { - IDataFilter DataFilter { get; } + IDataFilter DataFilter { get; } - ISelect Select { get; } + ISelect Select { get; } - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); - } + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); + } - public interface IReadOnlyRepository : IReadOnlyRepository - where TEntity : class { - TEntity Get(TKey id); + public interface IReadOnlyRepository : IReadOnlyRepository + where TEntity : class + { + TEntity Get(TKey id); - Task GetAsync(TKey id); + Task GetAsync(TKey id); - TEntity Find(TKey id); + TEntity Find(TKey id); - Task FindAsync(TKey id); - } + Task FindAsync(TKey id); + } } diff --git a/FreeSql.DbContext/TempExtensions.cs b/FreeSql.DbContext/TempExtensions.cs index fbb7bd53..43528138 100644 --- a/FreeSql.DbContext/TempExtensions.cs +++ b/FreeSql.DbContext/TempExtensions.cs @@ -1,5 +1,7 @@  -namespace FreeSql.Extensions.EntityUtil { - public static class TempExtensions { - } +namespace FreeSql.Extensions.EntityUtil +{ + public static class TempExtensions + { + } } diff --git a/FreeSql.DbContext/UnitOfWork/IUnitOfWork.cs b/FreeSql.DbContext/UnitOfWork/IUnitOfWork.cs index 8ded92ff..ca1a7acd 100644 --- a/FreeSql.DbContext/UnitOfWork/IUnitOfWork.cs +++ b/FreeSql.DbContext/UnitOfWork/IUnitOfWork.cs @@ -2,12 +2,14 @@ using System.Data; using System.Data.Common; -namespace FreeSql { - public interface IUnitOfWork : IDisposable { +namespace FreeSql +{ + public interface IUnitOfWork : IDisposable + { - DbTransaction GetOrBeginTransaction(bool isCreate = true); + DbTransaction GetOrBeginTransaction(bool isCreate = true); - IsolationLevel? IsolationLevel { get; set; } + IsolationLevel? IsolationLevel { get; set; } /// /// 是否启用工作单元 @@ -16,7 +18,7 @@ namespace FreeSql { void Commit(); - void Rollback(); + void Rollback(); /// /// 禁用工作单元 diff --git a/FreeSql.DbContext/UnitOfWork/UnitOfWork.cs b/FreeSql.DbContext/UnitOfWork/UnitOfWork.cs index 5cbaf016..a11edae8 100644 --- a/FreeSql.DbContext/UnitOfWork/UnitOfWork.cs +++ b/FreeSql.DbContext/UnitOfWork/UnitOfWork.cs @@ -3,22 +3,26 @@ using System; using System.Data; using System.Data.Common; -namespace FreeSql { - class UnitOfWork : IUnitOfWork { +namespace FreeSql +{ + class UnitOfWork : IUnitOfWork + { - protected IFreeSql _fsql; - protected Object _conn; - protected DbTransaction _tran; + protected IFreeSql _fsql; + protected Object _conn; + protected DbTransaction _tran; - public UnitOfWork(IFreeSql fsql) { - _fsql = fsql; - } + public UnitOfWork(IFreeSql fsql) + { + _fsql = fsql; + } - void ReturnObject() { - _fsql.Ado.MasterPool.Return(_conn); - _tran = null; - _conn = null; - } + void ReturnObject() + { + _fsql.Ado.MasterPool.Return(_conn); + _tran = null; + _conn = null; + } /// @@ -49,55 +53,74 @@ namespace FreeSql { public IsolationLevel? IsolationLevel { get; set; } - public DbTransaction GetOrBeginTransaction(bool isCreate = true) { + public DbTransaction GetOrBeginTransaction(bool isCreate = true) + { - if (_tran != null) return _tran; - if (isCreate == false) return null; + if (_tran != null) return _tran; + if (isCreate == false) return null; if (!Enable) return null; - if (_conn != null) _fsql.Ado.MasterPool.Return(_conn); + if (_conn != null) _fsql.Ado.MasterPool.Return(_conn); - _conn = _fsql.Ado.MasterPool.Get(); - try { - _tran = IsolationLevel == null ? - _conn.Value.BeginTransaction() : - _conn.Value.BeginTransaction(IsolationLevel.Value); - } catch { - ReturnObject(); - throw; - } - return _tran; - } + _conn = _fsql.Ado.MasterPool.Get(); + try + { + _tran = IsolationLevel == null ? + _conn.Value.BeginTransaction() : + _conn.Value.BeginTransaction(IsolationLevel.Value); + } + catch + { + ReturnObject(); + throw; + } + return _tran; + } - public void Commit() { - if (_tran != null) { - try { - _tran.Commit(); - } finally { - ReturnObject(); - } - } - } - public void Rollback() { - if (_tran != null) { - try { - _tran.Rollback(); - } finally { - ReturnObject(); - } - } - } - ~UnitOfWork() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - try { - this.Rollback(); - } finally { - _isdisposed = true; - GC.SuppressFinalize(this); - } - } - } + public void Commit() + { + if (_tran != null) + { + try + { + _tran.Commit(); + } + finally + { + ReturnObject(); + } + } + } + public void Rollback() + { + if (_tran != null) + { + try + { + _tran.Rollback(); + } + finally + { + ReturnObject(); + } + } + } + ~UnitOfWork() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + try + { + this.Rollback(); + } + finally + { + _isdisposed = true; + GC.SuppressFinalize(this); + } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.DbContext/RepositoryTests.cs b/FreeSql.Tests/FreeSql.Tests.DbContext/RepositoryTests.cs index da499384..b2be4440 100644 --- a/FreeSql.Tests/FreeSql.Tests.DbContext/RepositoryTests.cs +++ b/FreeSql.Tests/FreeSql.Tests.DbContext/RepositoryTests.cs @@ -1,118 +1,132 @@ using System; using Xunit; -namespace FreeSql.Tests { - public class RepositoryTests { +namespace FreeSql.Tests +{ + public class RepositoryTests + { - [Fact] - public void AddUpdate() { - var repos = g.sqlite.GetGuidRepository(); + [Fact] + public void AddUpdate() + { + var repos = g.sqlite.GetGuidRepository(); - var item = repos.Insert(new AddUpdateInfo()); - Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); + var item = repos.Insert(new AddUpdateInfo()); + Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); - item = repos.Insert(new AddUpdateInfo { Id = Guid.NewGuid() }); - Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); + item = repos.Insert(new AddUpdateInfo { Id = Guid.NewGuid() }); + Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); - item.Title = "xxx"; - repos.Update(item); - Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); + item.Title = "xxx"; + repos.Update(item); + Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); - Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql()); - repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows(); + Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql()); + repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows(); - item = repos.Find(item.Id); - Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); - } + item = repos.Find(item.Id); + Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); + } - [Fact] - public void UpdateAttach() { - var repos = g.sqlite.GetGuidRepository(); + [Fact] + public void UpdateAttach() + { + var repos = g.sqlite.GetGuidRepository(); - var item = new AddUpdateInfo { Id = Guid.NewGuid() }; - repos.Attach(item); + var item = new AddUpdateInfo { Id = Guid.NewGuid() }; + repos.Attach(item); - item.Title = "xxx"; - repos.Update(item); - Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); + item.Title = "xxx"; + repos.Update(item); + Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); - Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql()); - repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows(); + Console.WriteLine(repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ToSql()); + repos.UpdateDiy.Where(a => a.Id == item.Id).Set(a => a.Clicks + 1).ExecuteAffrows(); - item = repos.Find(item.Id); - Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); - } + item = repos.Find(item.Id); + Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); + } - [Fact] - public void UpdateWhenNotExists() { - var repos = g.sqlite.GetGuidRepository(); + [Fact] + public void UpdateWhenNotExists() + { + var repos = g.sqlite.GetGuidRepository(); - var item = new AddUpdateInfo { Id = Guid.NewGuid() }; - item.Title = "xxx"; - Assert.Throws(() => repos.Update(item)); - } + var item = new AddUpdateInfo { Id = Guid.NewGuid() }; + item.Title = "xxx"; + Assert.Throws(() => repos.Update(item)); + } - [Fact] - public void Update() { - g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows(); + [Fact] + public void Update() + { + g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows(); - var repos = g.sqlite.GetGuidRepository(); + var repos = g.sqlite.GetGuidRepository(); - var item = new AddUpdateInfo { Id = g.sqlite.Select().First().Id }; + var item = new AddUpdateInfo { Id = g.sqlite.Select().First().Id }; - item.Title = "xxx"; - repos.Update(item); - Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); - } + item.Title = "xxx"; + repos.Update(item); + Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(item)); + } - public class AddUpdateInfo { + public class AddUpdateInfo + { - public Guid Id { get; set; } - public string Title { get; set; } + public Guid Id { get; set; } + public string Title { get; set; } - public int Clicks { get; set; } = 10; - } + public int Clicks { get; set; } = 10; + } - [Fact] - public void UnitOfWorkRepository() { - foreach (var fsql in new[] { g.sqlite, /*g.mysql, g.pgsql, g.oracle, g.sqlserver*/ }) { + [Fact] + public void UnitOfWorkRepository() + { + foreach (var fsql in new[] { g.sqlite, /*g.mysql, g.pgsql, g.oracle, g.sqlserver*/ }) + { - fsql.CodeFirst.ConfigEntity(f => { - f.Property(b => b.UserId).IsPrimary(true); - f.Property(b => b.Id).IsPrimary(true).IsIdentity(true); - f.Property(b => b.Name).IsNullable(false); - }); + fsql.CodeFirst.ConfigEntity(f => + { + f.Property(b => b.UserId).IsPrimary(true); + f.Property(b => b.Id).IsPrimary(true).IsIdentity(true); + f.Property(b => b.Name).IsNullable(false); + }); - FlowModel flow = new FlowModel() { - CreateTime = DateTime.Now, - Name = "aaa", - LastModifyTime = DateTime.Now, - UserId = 1, - }; - var flowRepos = fsql.GetRepository(); - flowRepos.Insert(flow); + FlowModel flow = new FlowModel() + { + CreateTime = DateTime.Now, + Name = "aaa", + LastModifyTime = DateTime.Now, + UserId = 1, + }; + var flowRepos = fsql.GetRepository(); + flowRepos.Insert(flow); - // - flow = new FlowModel() { - CreateTime = DateTime.Now, - Name = "aaa", - LastModifyTime = DateTime.Now, - UserId = 1, - }; - using (var uow = fsql.CreateUnitOfWork()) { - flowRepos = uow.GetRepository(); - flowRepos.Insert(flow); - uow.Commit(); - } + // + flow = new FlowModel() + { + CreateTime = DateTime.Now, + Name = "aaa", + LastModifyTime = DateTime.Now, + UserId = 1, + }; + using (var uow = fsql.CreateUnitOfWork()) + { + flowRepos = uow.GetRepository(); + flowRepos.Insert(flow); + uow.Commit(); + } } - } + } [Fact] public void UnitOfWorkRepositoryWithDisableBeforeInsert() { - foreach (var fsql in new[] { g.sqlite, }) + foreach (var fsql in new[] { g.sqlite, }) { - fsql.CodeFirst.ConfigEntity(f => { + fsql.CodeFirst.ConfigEntity(f => + { f.Property(b => b.UserId).IsPrimary(true); f.Property(b => b.Id).IsPrimary(true).IsIdentity(true); f.Property(b => b.Name).IsNullable(false); @@ -129,7 +143,7 @@ namespace FreeSql.Tests { }; //ݿѴڵݣΪ˽IJ - flowRepos.Delete(a => a.UserId == 1 &&a.Name== "aaa"); + flowRepos.Delete(a => a.UserId == 1 && a.Name == "aaa"); using (var uow = fsql.CreateUnitOfWork()) { @@ -140,7 +154,7 @@ namespace FreeSql.Tests { //ѹرչԪ᲻ύûӰ죬˴עȷԪǷЧرˣCommitҲӦò //uow.Commit(); } - + Assert.True(flowRepos.Select.Any(a => a.UserId == 1 && a.Name == "aaa")); } @@ -149,7 +163,7 @@ namespace FreeSql.Tests { [Fact] public void UnitOfWorkRepositoryWithDisableAfterInsert() { - foreach (var fsql in new[] {g.sqlite,}) + foreach (var fsql in new[] { g.sqlite, }) { fsql.CodeFirst.ConfigEntity(f => { @@ -227,35 +241,37 @@ namespace FreeSql.Tests { } - public partial class FlowModel { - public int UserId { get; set; } - public int Id { get; set; } - public int? ParentId { get; set; } - public string Name { get; set; } - public DateTime CreateTime { get; set; } - public DateTime LastModifyTime { get; set; } - public string Desc { get; set; } - } + public partial class FlowModel + { + public int UserId { get; set; } + public int Id { get; set; } + public int? ParentId { get; set; } + public string Name { get; set; } + public DateTime CreateTime { get; set; } + public DateTime LastModifyTime { get; set; } + public string Desc { get; set; } + } - [Fact] - public void AsType() { - g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows(); + [Fact] + public void AsType() + { + g.sqlite.Insert(new AddUpdateInfo()).ExecuteAffrows(); - var repos = g.sqlite.GetGuidRepository(); - repos.AsType(typeof(AddUpdateInfo)); + var repos = g.sqlite.GetGuidRepository(); + repos.AsType(typeof(AddUpdateInfo)); - var item = new AddUpdateInfo(); - repos.Insert(item); - repos.Update(item); + var item = new AddUpdateInfo(); + repos.Insert(item); + repos.Update(item); - item.Clicks += 1; - repos.InsertOrUpdate(item); + item.Clicks += 1; + repos.InsertOrUpdate(item); - var item2 = repos.Find(item.Id) as AddUpdateInfo; - Assert.Equal(item.Clicks, item2.Clicks); + var item2 = repos.Find(item.Id) as AddUpdateInfo; + Assert.Equal(item.Clicks, item2.Clicks); - repos.DataFilter.Apply("xxx", a => (a as AddUpdateInfo).Clicks == 2); - Assert.Null(repos.Find(item.Id)); - } - } + repos.DataFilter.Apply("xxx", a => (a as AddUpdateInfo).Clicks == 2); + Assert.Null(repos.Find(item.Id)); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.DbContext/UnitTest1.cs b/FreeSql.Tests/FreeSql.Tests.DbContext/UnitTest1.cs index 0bbc0c4a..ea2a7435 100644 --- a/FreeSql.Tests/FreeSql.Tests.DbContext/UnitTest1.cs +++ b/FreeSql.Tests/FreeSql.Tests.DbContext/UnitTest1.cs @@ -6,155 +6,175 @@ using Xunit; using System.Linq; using Newtonsoft.Json.Linq; -namespace FreeSql.Tests { - public class UnitTest1 { +namespace FreeSql.Tests +{ + public class UnitTest1 + { - class testenumWhere { - public Guid id { get; set; } - public testenumWhereType type { get; set; } - } - public enum testenumWhereType { Menu, Class, Blaaa } + class testenumWhere + { + public Guid id { get; set; } + public testenumWhereType type { get; set; } + } + public enum testenumWhereType { Menu, Class, Blaaa } - [Fact] - public void Include_ManyToMany() { + [Fact] + public void Include_ManyToMany() + { - g.sqlite.CodeFirst.SyncStructure(); - g.sqlite.CodeFirst.SyncStructure(); - g.sqlite.CodeFirst.SyncStructure(); + g.sqlite.CodeFirst.SyncStructure(); + g.sqlite.CodeFirst.SyncStructure(); + g.sqlite.CodeFirst.SyncStructure(); - using (var ctx = g.sqlite.CreateDbContext()) { + using (var ctx = g.sqlite.CreateDbContext()) + { - var songs = ctx.Set().Select - .IncludeMany(a => a.Tags) - .ToList(); + var songs = ctx.Set().Select + .IncludeMany(a => a.Tags) + .ToList(); - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_01_й" - }; - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_02_" - }; - var tag3 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_03_ձ" - }; - ctx.AddRange(new[] { tag1, tag2, tag3 }); + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_01_й" + }; + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_02_" + }; + var tag3 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_03_ձ" + }; + ctx.AddRange(new[] { tag1, tag2, tag3 }); - var song1 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_01_й.mp3", - Url = "http://ww.baidu.com/" - }; - var song2 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_02_һ.mp3", - Url = "http://ww.163.com/" - }; - var song3 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_03_ǧһ.mp3", - Url = "http://ww.sina.com/" - }; - ctx.AddRange(new[] { song1, song2, song3 }); + var song1 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_01_й.mp3", + Url = "http://ww.baidu.com/" + }; + var song2 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_02_һ.mp3", + Url = "http://ww.163.com/" + }; + var song3 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_03_ǧһ.mp3", + Url = "http://ww.sina.com/" + }; + ctx.AddRange(new[] { song1, song2, song3 }); - ctx.AddRange( - new[] { - new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }, - new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }, - new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }, - new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }, - new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }, - new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }, - } - ); - ctx.SaveChanges(); - } - } + ctx.AddRange( + new[] { + new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }, + new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }, + new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }, + new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }, + new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }, + new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }, + } + ); + ctx.SaveChanges(); + } + } - [Fact] - public void Add() { + [Fact] + public void Add() + { - g.sqlite.SetDbContextOptions(opt => { - //opt.EnableAddOrUpdateNavigateList = false; - }); + g.sqlite.SetDbContextOptions(opt => + { + //opt.EnableAddOrUpdateNavigateList = false; + }); - g.mysql.Insert().AppendData(new testenumWhere { type = testenumWhereType.Blaaa }).ExecuteAffrows(); + g.mysql.Insert().AppendData(new testenumWhere { type = testenumWhereType.Blaaa }).ExecuteAffrows(); - var sql = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToSql(); - var tolist = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToList(); + var sql = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToSql(); + var tolist = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToList(); - //֧ 1Զ + //֧ 1Զ - using (var ctx = new FreeContext(g.sqlite)) { + using (var ctx = new FreeContext(g.sqlite)) + { - var tags = ctx.Set().Select.IncludeMany(a => a.Tags).ToList(); + var tags = ctx.Set().Select.IncludeMany(a => a.Tags).ToList(); - var tag = new Tag { - Name = "testaddsublist", - Tags = new[] { - new Tag { Name = "sub1" }, - new Tag { Name = "sub2" }, - new Tag { - Name = "sub3", - Tags = new[] { - new Tag { Name = "sub3_01" } - } - } - } - }; - ctx.Add(tag); - ctx.SaveChanges(); - } - } + var tag = new Tag + { + Name = "testaddsublist", + Tags = new[] { + new Tag { Name = "sub1" }, + new Tag { Name = "sub2" }, + new Tag { + Name = "sub3", + Tags = new[] { + new Tag { Name = "sub3_01" } + } + } + } + }; + ctx.Add(tag); + ctx.SaveChanges(); + } + } - [Fact] - public void Update() { - //ѯ 1Զ࣬ + [Fact] + public void Update() + { + //ѯ 1Զ࣬ - using (var ctx = new FreeContext(g.sqlite)) { + using (var ctx = new FreeContext(g.sqlite)) + { - var tag = ctx.Set().Select.First(); - tag.Tags.Add(new Tag { Name = "sub3" }); - ctx.Update(tag); - ctx.SaveChanges(); - } - } + var tag = ctx.Set().Select.First(); + tag.Tags.Add(new Tag { Name = "sub3" }); + ctx.Update(tag); + ctx.SaveChanges(); + } + } - public class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } + public class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } - public virtual ICollection Tags { get; set; } + public virtual ICollection Tags { get; set; } - [Column(IsVersion = true)] - public long versionRow { get; set; } - } - public class Song_tag { - public int Song_id { get; set; } - public virtual Song Song { get; set; } + [Column(IsVersion = true)] + public long versionRow { get; set; } + } + public class Song_tag + { + public int Song_id { get; set; } + public virtual Song Song { get; set; } - public int Tag_id { get; set; } - public virtual Tag Tag { get; set; } - } + public int Tag_id { get; set; } + public virtual Tag Tag { get; set; } + } - public class Tag { - [Column(IsIdentity = true)] - public int Id { get; set; } - public int? Parent_id { get; set; } - public virtual Tag Parent { get; set; } + public class Tag + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public int? Parent_id { get; set; } + public virtual Tag Parent { get; set; } - public decimal? Ddd { get; set; } - public string Name { get; set; } + public decimal? Ddd { get; set; } + public string Name { get; set; } - public virtual ICollection Songs { get; set; } - public virtual ICollection Tags { get; set; } - } - } + public virtual ICollection Songs { get; set; } + public virtual ICollection Tags { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.DbContext/g.cs b/FreeSql.Tests/FreeSql.Tests.DbContext/g.cs index 4aec7356..6bb48a5e 100644 --- a/FreeSql.Tests/FreeSql.Tests.DbContext/g.cs +++ b/FreeSql.Tests/FreeSql.Tests.DbContext/g.cs @@ -4,83 +4,94 @@ using System.Diagnostics; using System.Text; -public class g { +public class g +{ - static Lazy sqlserverLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .UseLazyLoading(true) - .UseNoneCommandParameter(true) - .Build()); - public static IFreeSql sqlserver => sqlserverLazy.Value; + static Lazy sqlserverLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .UseLazyLoading(true) + .UseNoneCommandParameter(true) + .Build()); + public static IFreeSql sqlserver => sqlserverLazy.Value; - static Lazy mysqlLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10") - .UseAutoSyncStructure(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .UseLazyLoading(true) - .UseNoneCommandParameter(true) - .Build()); - public static IFreeSql mysql => mysqlLazy.Value; + static Lazy mysqlLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10") + .UseAutoSyncStructure(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .UseLazyLoading(true) + .UseNoneCommandParameter(true) + .Build()); + public static IFreeSql mysql => mysqlLazy.Value; - static Lazy pgsqlLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10") - .UseAutoSyncStructure(true) - .UseSyncStructureToLower(true) - .UseLazyLoading(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .UseNoneCommandParameter(true) - .Build()); - public static IFreeSql pgsql => pgsqlLazy.Value; + static Lazy pgsqlLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10") + .UseAutoSyncStructure(true) + .UseSyncStructureToLower(true) + .UseLazyLoading(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .UseNoneCommandParameter(true) + .Build()); + public static IFreeSql pgsql => pgsqlLazy.Value; - static Lazy oracleLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseLazyLoading(true) - .UseSyncStructureToUpper(true) - .UseNoneCommandParameter(true) + static Lazy oracleLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseLazyLoading(true) + .UseSyncStructureToUpper(true) + .UseNoneCommandParameter(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .Build()); - public static IFreeSql oracle => oracleLazy.Value; + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .Build()); + public static IFreeSql oracle => oracleLazy.Value; - static Lazy sqliteLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|/document22.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseLazyLoading(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .UseNoneCommandParameter(true) - .Build()); - public static IFreeSql sqlite => sqliteLazy.Value; + static Lazy sqliteLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|/document22.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseLazyLoading(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .UseNoneCommandParameter(true) + .Build()); + public static IFreeSql sqlite => sqliteLazy.Value; } diff --git a/FreeSql.Tests/FreeSql.Tests.PerformanceTests/MySqlAdoTest.cs b/FreeSql.Tests/FreeSql.Tests.PerformanceTests/MySqlAdoTest.cs index e523097f..147241ad 100644 --- a/FreeSql.Tests/FreeSql.Tests.PerformanceTests/MySqlAdoTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.PerformanceTests/MySqlAdoTest.cs @@ -9,191 +9,216 @@ using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; -namespace FreeSql.Tests.PerformanceTest { - public class MySqlAdoTest { +namespace FreeSql.Tests.PerformanceTest +{ + public class MySqlAdoTest + { - [Fact] - public void Query() { - var sb = new StringBuilder(); - var time = new Stopwatch(); + [Fact] + public void Query() + { + var sb = new StringBuilder(); + var time = new Stopwatch(); - time.Restart(); - List dplist1 = null; - using (var conn = g.mysql.Ado.MasterPool.Get()) { - dplist1 = Dapper.SqlMapper.Query(conn.Value, "select * from song").ToList(); - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper"); + time.Restart(); + List dplist1 = null; + using (var conn = g.mysql.Ado.MasterPool.Get()) + { + dplist1 = Dapper.SqlMapper.Query(conn.Value, "select * from song").ToList(); + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper"); - time.Restart(); - List<(int, string, string)> dplist2 = null; - using (var conn = g.mysql.Ado.MasterPool.Get()) { - dplist2 = Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song").ToList(); - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper"); + time.Restart(); + List<(int, string, string)> dplist2 = null; + using (var conn = g.mysql.Ado.MasterPool.Get()) + { + dplist2 = Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song").ToList(); + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper"); - time.Restart(); - List dplist3 = null; - using (var conn = g.mysql.Ado.MasterPool.Get()) { - dplist3 = Dapper.SqlMapper.Query(conn.Value, "select * from song").ToList(); - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper"); + time.Restart(); + List dplist3 = null; + using (var conn = g.mysql.Ado.MasterPool.Get()) + { + dplist3 = Dapper.SqlMapper.Query(conn.Value, "select * from song").ToList(); + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper"); - var t31 = g.mysql.Ado.Query("select * from song limit 1"); + var t31 = g.mysql.Ado.Query("select * from song limit 1"); - time.Restart(); - var t3 = g.mysql.Ado.Query("select * from song"); - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*"); + time.Restart(); + var t3 = g.mysql.Ado.Query("select * from song"); + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*"); - time.Restart(); - var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song"); - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*"); + time.Restart(); + var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song"); + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*"); - time.Restart(); - var t41 = g.mysql.Select().ToList<(int, string, string)>("id,title,url"); - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query ToList Counts: {t41.Count}; ORM: FreeSql*"); + time.Restart(); + var t41 = g.mysql.Select().ToList<(int, string, string)>("id,title,url"); + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query ToList Counts: {t41.Count}; ORM: FreeSql*"); - time.Restart(); - var t5 = g.mysql.Ado.Query("select * from song"); - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*"); + time.Restart(); + var t5 = g.mysql.Ado.Query("select * from song"); + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*"); - } + } - [Fact] - public void QueryLimit10() { - var sb = new StringBuilder(); - var time = new Stopwatch(); + [Fact] + public void QueryLimit10() + { + var sb = new StringBuilder(); + var time = new Stopwatch(); - time.Restart(); - List dplist1 = new List(); - for (var a = 0; a < 10000; a++) { - using (var conn = g.mysql.Ado.MasterPool.Get()) { - dplist1.AddRange(Dapper.SqlMapper.Query(conn.Value, "select * from song limit 10").ToList()); - } - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper"); + time.Restart(); + List dplist1 = new List(); + for (var a = 0; a < 10000; a++) + { + using (var conn = g.mysql.Ado.MasterPool.Get()) + { + dplist1.AddRange(Dapper.SqlMapper.Query(conn.Value, "select * from song limit 10").ToList()); + } + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper"); - time.Restart(); - List<(int, string, string)> dplist2 = new List<(int, string, string)>(); - for (var a = 0; a < 10000; a++) { - using (var conn = g.mysql.Ado.MasterPool.Get()) { - dplist2.AddRange(Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song limit 10").ToList()); - } - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper"); + time.Restart(); + List<(int, string, string)> dplist2 = new List<(int, string, string)>(); + for (var a = 0; a < 10000; a++) + { + using (var conn = g.mysql.Ado.MasterPool.Get()) + { + dplist2.AddRange(Dapper.SqlMapper.Query<(int, string, string)>(conn.Value, "select * from song limit 10").ToList()); + } + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {dplist2.Count}; ORM: Dapper"); - time.Restart(); - List dplist3 = new List(); - for (var a = 0; a < 10000; a++) { - using (var conn = g.mysql.Ado.MasterPool.Get()) { - dplist3.AddRange(Dapper.SqlMapper.Query(conn.Value, "select * from song limit 10").ToList()); - } - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper"); + time.Restart(); + List dplist3 = new List(); + for (var a = 0; a < 10000; a++) + { + using (var conn = g.mysql.Ado.MasterPool.Get()) + { + dplist3.AddRange(Dapper.SqlMapper.Query(conn.Value, "select * from song limit 10").ToList()); + } + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {dplist3.Count}; ORM: Dapper"); - time.Restart(); - List t3 = new List(); - for (var a = 0; a < 10000; a++) { - t3.AddRange(g.mysql.Ado.Query("select * from song limit 10")); - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*"); + time.Restart(); + List t3 = new List(); + for (var a = 0; a < 10000; a++) + { + t3.AddRange(g.mysql.Ado.Query("select * from song limit 10")); + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {t3.Count}; ORM: FreeSql*"); - time.Restart(); - List<(int, string, string)> t4 = new List<(int, string, string)>(); - for (var a = 0; a < 10000; a++) { - t4.AddRange(g.mysql.Ado.Query<(int, string, string)>("select * from song limit 10")); - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*"); + time.Restart(); + List<(int, string, string)> t4 = new List<(int, string, string)>(); + for (var a = 0; a < 10000; a++) + { + t4.AddRange(g.mysql.Ado.Query<(int, string, string)>("select * from song limit 10")); + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Tuple Counts: {t4.Count}; ORM: FreeSql*"); - time.Restart(); - List t5 = new List(); - for (var a = 0; a < 10000; a++) { - t5.AddRange(g.mysql.Ado.Query("select * from song limit 10")); - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*"); + time.Restart(); + List t5 = new List(); + for (var a = 0; a < 10000; a++) + { + t5.AddRange(g.mysql.Ado.Query("select * from song limit 10")); + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Dynamic Counts: {t3.Count}; ORM: FreeSql*"); - } + } - [Fact] - public void ToList() { - var sb = new StringBuilder(); - var time = new Stopwatch(); + [Fact] + public void ToList() + { + var sb = new StringBuilder(); + var time = new Stopwatch(); - //var t31 = g.mysql.Select().ToList(); + //var t31 = g.mysql.Select().ToList(); - time.Restart(); - var t3 = g.mysql.Select().ToList(); - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3.Count}; ORM: FreeSql*"); + time.Restart(); + var t3 = g.mysql.Select().ToList(); + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3.Count}; ORM: FreeSql*"); - time.Restart(); - List dplist1 = null; - using (var conn = g.mysql.Ado.MasterPool.Get()) { - dplist1 = Dapper.SqlMapper.Query(conn.Value, "select * from song").ToList(); - } - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper"); - } + time.Restart(); + List dplist1 = null; + using (var conn = g.mysql.Ado.MasterPool.Get()) + { + dplist1 = Dapper.SqlMapper.Query(conn.Value, "select * from song").ToList(); + } + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1.Count}; ORM: Dapper"); + } - [Fact] - public void ToListLimit10() { - var sb = new StringBuilder(); - var time = new Stopwatch(); + [Fact] + public void ToListLimit10() + { + var sb = new StringBuilder(); + var time = new Stopwatch(); - time.Restart(); - var t3Count = 0; - var p3 = Parallel.For(1, 50, b => { - List t3 = new List(); - for (var a = 0; a < 1000; a++) { - t3.AddRange(g.mysql.Select().Limit(50).ToList()); - } - Interlocked.Add(ref t3Count, t3.Count); - }); - while (p3.IsCompleted == false) ; - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3Count}; ORM: FreeSql*"); + time.Restart(); + var t3Count = 0; + var p3 = Parallel.For(1, 50, b => + { + List t3 = new List(); + for (var a = 0; a < 1000; a++) + { + t3.AddRange(g.mysql.Select().Limit(50).ToList()); + } + Interlocked.Add(ref t3Count, t3.Count); + }); + while (p3.IsCompleted == false) ; + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; ToList Entity Counts: {t3Count}; ORM: FreeSql*"); - time.Restart(); - var dplist1Count = 0; - var p1 = Parallel.For(1, 50, b => { - List dplist1 = new List(); - for (var a = 0; a < 1000; a++) { - using (var conn = g.mysql.Ado.MasterPool.Get()) { - dplist1.AddRange(Dapper.SqlMapper.Query(conn.Value, "select * from song limit 50").ToList()); - } - } - Interlocked.Add(ref dplist1Count, dplist1.Count); - }); - while (p1.IsCompleted == false) ; - time.Stop(); - sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1Count}; ORM: Dapper"); - } + time.Restart(); + var dplist1Count = 0; + var p1 = Parallel.For(1, 50, b => + { + List dplist1 = new List(); + for (var a = 0; a < 1000; a++) + { + using (var conn = g.mysql.Ado.MasterPool.Get()) + { + dplist1.AddRange(Dapper.SqlMapper.Query(conn.Value, "select * from song limit 50").ToList()); + } + } + Interlocked.Add(ref dplist1Count, dplist1.Count); + }); + while (p1.IsCompleted == false) ; + time.Stop(); + sb.AppendLine($"Elapsed: {time.Elapsed}; Query Entity Counts: {dplist1Count}; ORM: Dapper"); + } - [Table(Name = "song")] - class xxx { - public int Id { get; set; } - public string Title { get; set; } - //public string Url { get; set; } - public DateTime Create_time { get; set; } - public bool Is_deleted { get; set; } - } - } + [Table(Name = "song")] + class xxx + { + public int Id { get; set; } + public string Title { get; set; } + //public string Url { get; set; } + public DateTime Create_time { get; set; } + public bool Is_deleted { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.PerformanceTests/g.cs b/FreeSql.Tests/FreeSql.Tests.PerformanceTests/g.cs index ceb1c0a1..8a8d4d3e 100644 --- a/FreeSql.Tests/FreeSql.Tests.PerformanceTests/g.cs +++ b/FreeSql.Tests/FreeSql.Tests.PerformanceTests/g.cs @@ -3,31 +3,32 @@ using System.Collections.Generic; using System.Text; -public class g { +public class g +{ - public static IFreeSql mysql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=100") - .UseAutoSyncStructure(false) - .Build(); + public static IFreeSql mysql = new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=100") + .UseAutoSyncStructure(false) + .Build(); - //public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder() - // .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=cms;Pooling=true;Max Pool Size=10") - // .UseAutoSyncStructure(false) - // .Build(); + //public static IFreeSql sqlserver = new FreeSql.FreeSqlBuilder() + // .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=cms;Pooling=true;Max Pool Size=10") + // .UseAutoSyncStructure(false) + // .Build(); - //public static IFreeSql pgsql = new FreeSql.FreeSqlBuilder() - // .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10") - // .UseAutoSyncStructure(false) - // .UseSyncStructureToLower(true) - // .Build(); + //public static IFreeSql pgsql = new FreeSql.FreeSqlBuilder() + // .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10") + // .UseAutoSyncStructure(false) + // .UseSyncStructureToLower(true) + // .Build(); - //public static IFreeSql oracle = new FreeSql.FreeSqlBuilder() - // .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") - // .UseAutoSyncStructure(false) - // .Build(); + //public static IFreeSql oracle = new FreeSql.FreeSqlBuilder() + // .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") + // .UseAutoSyncStructure(false) + // .Build(); - //public static IFreeSql sqlite = new FreeSql.FreeSqlBuilder() - // .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10") - // .UseAutoSyncStructure(false) - // .Build(); + //public static IFreeSql sqlite = new FreeSql.FreeSqlBuilder() + // .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10") + // .UseAutoSyncStructure(false) + // .Build(); } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlDeleteTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlDeleteTest.cs index fe402ce3..52704fea 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlDeleteTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlDeleteTest.cs @@ -4,84 +4,93 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnector { - public class MySqlDeleteTest { +namespace FreeSql.Tests.MySqlConnector +{ + public class MySqlDeleteTest + { - IDelete delete => g.mysql.Delete(); //�������� + IDelete delete => g.mysql.Delete(); //�������� - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void Dywhere() { - Assert.Null(g.mysql.Delete().ToSql()); - var sql = g.mysql.Delete(new[] { 1, 2 }).ToSql(); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(g.mysql.Delete().ToSql()); + var sql = g.mysql.Delete(new[] { 1, 2 }).ToSql(); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); - sql = g.mysql.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); + sql = g.mysql.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); - sql = g.mysql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); + sql = g.mysql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); - sql = g.mysql.Delete(new { id = 1 }).ToSql(); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); - } + sql = g.mysql.Delete(new { id = 1 }).ToSql(); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); + } - [Fact] - public void Where() { - var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); + [Fact] + public void Where() + { + var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); - sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql); + sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = delete.Where(item).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = delete.Where(item).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = delete.Where(items).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + sql = delete.Where(items).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - var id = g.mysql.Insert(new Topic { Title = "xxxx" }).ExecuteIdentity(); - Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); - } - [Fact] - public void ExecuteDeleted() { + var id = g.mysql.Insert(new Topic { Title = "xxxx" }).ExecuteIdentity(); + Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); + } + [Fact] + public void ExecuteDeleted() + { - //delete.Where(a => a.Id > 0).ExecuteDeleted(); - } + //delete.Where(a => a.Id > 0).ExecuteDeleted(); + } - [Fact] - public void AsTable() { - Assert.Null(g.mysql.Delete().ToSql()); - var sql = g.mysql.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); + [Fact] + public void AsTable() + { + Assert.Null(g.mysql.Delete().ToSql()); + var sql = g.mysql.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); - sql = g.mysql.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); + sql = g.mysql.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); - sql = g.mysql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); + sql = g.mysql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); - sql = g.mysql.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); - } - } + sql = g.mysql.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlInsertTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlInsertTest.cs index ff222517..26ac73fa 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlInsertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlInsertTest.cs @@ -4,132 +4,143 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnector { - public class MySqlInsertTest { +namespace FreeSql.Tests.MySqlConnector +{ + public class MySqlInsertTest + { - IInsert insert => g.mysql.Insert(); //�������� + IInsert insert => g.mysql.Insert(); //�������� - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestEnumInsertTb { - [Column(IsIdentity = true)] - public int id { get; set; } - public TestEnumInserTbType type { get; set; } - public DateTime time { get; set; } = new DateTime(); - } - enum TestEnumInserTbType { str1, biggit, sum211 } - - [Fact] - public void AppendData() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestEnumInsertTb + { + [Column(IsIdentity = true)] + public int id { get; set; } + public TestEnumInserTbType type { get; set; } + public DateTime time { get; set; } = new DateTime(); + } + enum TestEnumInserTbType { str1, biggit, sum211 } - var sql = insert.AppendData(items.First()).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); + [Fact] + public void AppendData() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); + var sql = insert.AppendData(items.First()).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.AppendData(items).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql(); - Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql); + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql(); - Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); - } + sql = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql(); + Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql); - [Fact] - public void InsertColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql(); + Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); + } - var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + [Fact] + public void InsertColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).InsertColumns(a =>new { a.Title, a.Clicks }).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - } - [Fact] - public void IgnoreColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + } + [Fact] + public void IgnoreColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); - } - [Fact] - public void ExecuteAffrows() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); + } + [Fact] + public void ExecuteAffrows() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - Assert.Equal(1, g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteAffrows()); - Assert.Equal(1, g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows()); - } - [Fact] - public void ExecuteIdentity() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); - Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); + Assert.Equal(1, g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteAffrows()); + Assert.Equal(1, g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows()); + } + [Fact] + public void ExecuteIdentity() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - var id = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteIdentity(); - Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select< TestEnumInsertTb>().Where(a => a.id == id).First()?.type); - id = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteIdentity(); - Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); - } - [Fact] - public void ExecuteInserted() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); - //insert.AppendData(items.First()).ExecuteInserted(); - } + var id = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteIdentity(); + Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); + id = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteIdentity(); + Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); + } + [Fact] + public void ExecuteInserted() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - [Fact] - public void AsTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + //insert.AppendData(items.First()).ExecuteInserted(); + } - var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); + [Fact] + public void AsTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); + var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); - } - } + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlSelectTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlSelectTest.cs index 19b22f96..ef2bda75 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlSelectTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlSelectTest.cs @@ -5,1227 +5,1307 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnector { - - public class MySqlSelectTest { - - ISelect select => g.mysql.Select(); - - [Table(Name = "tb_topic")] - public class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - [Column(OldName = "TypeGuid")] - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - - public virtual TopicFields Fields { get; set; } - } - public class TopicFields { - [Column(IsPrimary = true)] - public int TopicId { get; set; } - public virtual Topic Topic { get; set; } - } - public class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - - public int ParentId { get; set; } - public virtual TestTypeParentInfo Parent { get; set; } - - public string Name { get; set; } - - public virtual ICollection Topics { get; set; } - } - public class TestTypeParentInfo { - [Column(IsIdentity = true)] - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - - public partial class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } - - public virtual ICollection Tags { get; set; } - } - public partial class Song_tag { - public int Song_id { get; set; } - public virtual Song Song { get; set; } - - public int Tag_id { get; set; } - public virtual Tag Tag { get; set; } - } - public partial class Tag { - [Column(IsIdentity = true)] - public int Id { get; set; } - public int? Parent_id { get; set; } - public virtual Tag Parent { get; set; } - - public decimal? Ddd { get; set; } - public string Name { get; set; } - - public virtual ICollection Songs { get; set; } - public virtual ICollection Tags { get; set; } - } - - [Table(Name = "TestInfoT1", SelectFilter = " a.id > 0")] - class TestInfo { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - - [Fact] - public void AsSelect() { - //OneToOne、ManyToOne - var t0 = g.mysql.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 - //FROM `Tag` a - //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` - //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` - //WHERE (a__Parent__Parent.`Name` = '粤语') - - //OneToMany - var t1 = g.mysql.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` - //FROM `Tag` a - //WHERE (exists(SELECT 1 - // FROM `Tag` t - // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` - // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) - // limit 0,1)) - - //ManyToMany - var t2 = g.mysql.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); - //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` - //FROM `Song` a - //WHERE(exists(SELECT 1 - // FROM `Song_tag` Mt_Ms - // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 - // FROM `Tag` t - // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) - // limit 0, 1)) - // limit 0, 1)) - } - - [Fact] - public void Lazy() { - var tags = g.mysql.Select().Where(a => a.Parent.Name == "xxx") - .LeftJoin(a => a.Parent_id == a.Parent.Id) - .ToSql(); - - var songs = g.mysql.Select().Limit(10).ToList(); - } - - [Fact] - public void ToDataTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - - Assert.Equal(1, g.mysql.Insert().AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, g.mysql.Insert().AppendData(items).ExecuteAffrows()); - - //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - //Assert.Equal(9989, g.mysql.Insert(items).ExecuteAffrows()); - - var dt1 = select.Limit(10).ToDataTable(); - var dt2 = select.Limit(10).ToDataTable("id, 111222"); - var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); - } - - class TestDto { - public int id { get; set; } - public string name { get; set; } //这是join表的属性 - public int ParentId { get; set; } //这是join表的属性 - } - [Fact] - public void ToList() { - - var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto2 = select.Limit(10).ToList(a => new TestDto()); - var testDto3 = select.Limit(10).ToList(a => new TestDto { }); - var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); - var testDto5 = select.Limit(10).ToList(); - - var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); - var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); - var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); - var testDto55 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(); - - var t0 = select.Limit(50).ToList(); - - - var t1 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); - var t2 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); - - - var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToSql(); - var sql2 = select.LeftJoin((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToSql(); - var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToSql(); - - //g.mysql.Select().Join((a, b, c) => new Model.JoinResult3( - // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, - // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") - //); - - //var sql4 = select.From((a, b, c) => new SelectFrom() - // .InnerJoin(a.TypeGuid == b.Guid) - // .LeftJoin(c.Id == b.ParentId) - // .Where(b.Name == "xxx")) - //.Where(a => a.Id == 1).ToSql(); - - var sql4 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => c.Id == b.ParentId) - .Where(a => b.Name == "xxx")).ToSql(); - //.Where(a => a.Id == 1).ToSql(); - - - var list111 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => c.Id == b.ParentId) - .Where(a => b.Name != "xxx")); - var list111sql = list111.ToSql(); - var list111data = list111.ToList((a, b, c) => new { - a.Id, - title_substring = a.Title.Substring(0, 1), - a.Type, - ccc = new { a.Id, a.Title }, - tp = a.Type, - tp2 = new { - a.Id, - tp2 = a.Type.Name - }, - tp3 = new { - a.Id, - tp33 = new { - a.Id - } - } - }); - - var ttt122 = g.mysql.Select().Where(a => a.Id > 0).ToSql(); - var sql5 = g.mysql.Select().From((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToSql(); - var t11112 = g.mysql.Select().ToList(a => new { - a.Id, - a.Title, - a.Type, - ccc = new { a.Id, a.Title }, - tp = a.Type, - tp2 = new { - a.Id, - tp2 = a.Type.Name - }, - tp3 = new { - a.Id, - tp33 = new { - a.Id - } - } - - }); - - var t100 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - var t101 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - - - var t1111 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type }); - - var t2222 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type.Name }); - - g.mysql.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); - var testGuidId5 = g.mysql.Select().ToList(); - var testGuidId6 = g.mysql.Select().ToList(a => a.id); - - var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); - var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); - } - class TestGuidIdToList { - public Guid id { get; set; } - public string title { get; set; } = Guid.NewGuid().ToString(); - } - [Fact] - public void ToOne() { - var testnotfind = select.Where("1=2").First(a => a.CreateTime); - Assert.Equal(default(DateTime), testnotfind); - } - [Fact] - public void ToSql() { - g.mysql.Insert().AppendData(new testenumWhere { type = testenumWhereType.Blaaa }).ExecuteAffrows(); - - var sql1 = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToSql(); - var sql2 = g.mysql.Select().Where(a => testenumWhereType.Blaaa == a.type).ToSql(); - - var sql3 = g.mysql.Select().Where(a => a.type.Equals(testenumWhereType.Blaaa)).ToSql(); - var tolist = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToList(); - } - class testenumWhere { - public Guid id { get; set; } - public testenumWhereType type { get; set; } - } - public enum testenumWhereType { Menu, Class, Blaaa } - - [Fact] - public void Any() { - var count = select.Where(a => 1 == 1).Count(); - Assert.False(select.Where(a => 1 == 2).Any()); - Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); - - var sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && - select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - //.Offset(a.Id) - .Any() - ).Any(c => c.Id == a.Id + 10) - ); - var sql2222Tolist = sql2222.ToList(); - - var collectionSelect = select.Where(a => - a.Type.Guid == a.TypeGuid && - a.Type.Parent.Id == a.Type.ParentId && - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) - ); - collectionSelect.ToList(); - } - [Fact] - public void Count() { - var count = select.Where(a => 1 == 1).Count(); - select.Where(a => 1 == 1).Count(out var count2); - Assert.Equal(count, count2); - Assert.Equal(0, select.Where(a => 1 == 2).Count()); - } - [Fact] - public void Master() { - Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); - } - [Fact] - public void From() { - var query2 = select.From((s, b) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - ); - var sql2 = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid`", sql2); - query2.ToList(); - - var query3 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id) - ); - var sql3 = query3.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql3); - query3.ToList(); - } - [Fact] - public void LeftJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); - query.ToList(); - } - [Fact] - public void InnerJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //������� - query = select - .InnerJoin(a => a.Type.Guid == a.TypeGuid) - .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` INNER JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - query = select - .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .InnerJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` INNER JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .InnerJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` INNER JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); - query.ToList(); - - } - [Fact] - public void RightJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //������� - query = select - .RightJoin(a => a.Type.Guid == a.TypeGuid) - .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` RIGHT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - query = select - .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .RightJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` RIGHT JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .RightJoin(a => a.TypeGuid == b.Guid) - .RightJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` RIGHT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); - query.ToList(); - - } - [Fact] - public void Where() { - - var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); - var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); - var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); - - var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.Where(a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10)", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE ((a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100))", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10) AND (a.`Clicks` > 100)", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle')", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle' AND a__Type.`Guid` = a.`TypeGuid`)", sql); - query.ToList(); - - query = select.Where(a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Name` = 'tparent')", sql); - query.ToList(); - - //���û�е������ԣ��򵥶������ - query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b WHERE (b.`Guid` = a.`TypeGuid` AND b.`Name` = 'typeTitle')", sql); - query.ToList(); - - query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b WHERE (b.`Name` = 'typeTitle' AND b.`Guid` = a.`TypeGuid`)", sql); - query.ToList(); - - query = select.Where((a, b, c) => c.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeParentInfo` c WHERE (c.`Name` = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .Where(a => a.Id == 10 && c.Name == "xxx") - .Where(a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c WHERE (a.`Id` = 10 AND c.`Name` = 'xxx') AND (b.`ParentId` = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.Where("a.clicks > 100 and a.id = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.clicks > 100 and a.id = @id)", sql); - query.ToList(); - } - [Fact] - public void WhereIf() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.WhereIf(true, a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE ((a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100))", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10) AND (a.`Clicks` > 100)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle')", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle' AND a__Type.`Guid` = a.`TypeGuid`)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Name` = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(true, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c WHERE (a.`Id` = 10 AND c.`Name` = 'xxx') AND (b.`ParentId` = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(true, "a.clicks > 100 and a.id = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.clicks > 100 and a.id = @id)", sql); - query.ToList(); - - // ==========================================WhereIf(false) - - //����е�������a.Type��a.Type.Parent ���ǵ������� - query = select.WhereIf(false, a => a.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - query2 = select.From((s, b, c) => s - .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(false, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(false, "a.clicks > 100 and a.id = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - } - [Fact] - public void WhereExists() { - var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); - - sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - - //.Offset(a.Id) - - .Any() - ).Any() - ).ToList(); - } - [Fact] - public void GroupBy() { - var groupby = select.From((s, b, c) => s - .Where(a => a.Id == 1) - ) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()) - .Offset(10) - .Limit(2) - .ToList(a => new { - a.Key.tt2, - cou1 = a.Count(), - arg1 = a.Avg(a.Key.mod4), - ccc2 = a.Key.tt2 ?? "now()", - //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") - ccc3 = a.Max(a.Value.Item3.Id) - }); - - var testpid1 = g.mysql.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); - g.mysql.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); - - var aggsql1 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist1 = select - .GroupBy(a => a.Title) - .ToList(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToSql(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToList(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql3 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid), - sum3 = b.Sum(b.Value.Type.Parent.Id) - }); - } - [Fact] - public void ToAggregate() { - var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); - } - - [Fact] - public void OrderBy() { - var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); - } - [Fact] - public void Skip_Offset() { - var sql = select.Offset(10).Limit(10).ToList(); - } - [Fact] - public void Take_Limit() { - var sql = select.Limit(10).ToList(); - } - [Fact] - public void Page() { - var sql1 = select.Page(1, 10).ToList(); - var sql2 = select.Page(2, 10).ToList(); - var sql3 = select.Page(3, 10).ToList(); - - var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); - var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); - var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); - } - [Fact] - public void Distinct() { - var t1 = select.Distinct().ToList(a => a.Title); - var t2 = select.Distinct().Limit(10).ToList(a => a.Title); - } - - [Fact] - public void Sum() { - } - [Fact] - public void Min() { - } - [Fact] - public void Max() { - } - [Fact] - public void Avg() { - } - [Fact] - public void As() { - } - - [Fact] - public void AsTable() { - - var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); - - Func tableRule = (type, oldname) => { - if (type == typeof(Topic)) return oldname + "AsTable1"; - else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; - return oldname + "AsTable"; - }; - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid`", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); - - query = select - .LeftJoin((a, b) => b.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` c ON c.`Id` = a__Type.`ParentId`", sql); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfoAsTable` c ON b.`ParentId` = c.`Id`", sql); - - //������϶����㲻�� - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); - } - - public class TestInclude_OneToManyModel1 { - [Column(IsIdentity = true)] - public int id { get; set; } - public virtual TestInclude_OneToManyModel2 model2 { get; set; } - - public string m1name { get; set; } - } - public class TestInclude_OneToManyModel2 { - [Column(IsPrimary = true)] - public int model2id { get; set; } - public virtual TestInclude_OneToManyModel1 model1 { get; set; } - - public string m2setting { get; set; } - - public List childs { get; set; } - } - public class TestInclude_OneToManyModel3 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model2111Idaaa { get; set; } - public string title { get; set; } - - public List childs2 { get; set; } - } - public class TestInclude_OneToManyModel4 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model3333Id333 { get; set; } - public string title444 { get; set; } - } - - [Fact] - public void Include_OneToMany() { - var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; - model1.id = (int)g.mysql.Insert(model1).ExecuteIdentity(); - var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; - g.mysql.Insert(model2).ExecuteAffrows(); - - var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; - model3_1.id = (int)g.mysql.Insert(model3_1).ExecuteIdentity(); - var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; - model3_2.id = (int)g.mysql.Insert(model3_2).ExecuteIdentity(); - var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; - model3_3.id = (int)g.mysql.Insert(model3_2).ExecuteIdentity(); - - var model4s = new[] { - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } - }; - Assert.Equal(5, g.mysql.Insert(model4s).ExecuteAffrows()); - - var t0 = g.mysql.Select() - .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t1 = g.mysql.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t2 = g.mysql.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - - var t00 = g.mysql.Select() - .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t11 = g.mysql.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t22 = g.mysql.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - } - - public class TestInclude_OneToManyModel11 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2id { get; set; } - public string m3setting { get; set; } - public TestInclude_OneToManyModel22 model2 { get; set; } - public string m1name { get; set; } - } - - public class TestInclude_OneToManyModel22 { - [Column(IsIdentity = true)] - public int id { get; set; } - public string m2setting { get; set; } - public List childs { get; set; } - } - public class TestInclude_OneToManyModel33 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2Id { get; set; } - public string title { get; set; } - public string setting { get; set; } - } - [Fact] - public void Include_OneToMany2() { - string setting = "x"; - var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; - model2.id = (int)g.mysql.Insert(model2).ExecuteIdentity(); - - var model3s = new[] - { - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} - }; - Assert.Equal(3, g.mysql.Insert(model3s).ExecuteAffrows()); - - var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; - model1.id = (int)g.mysql.Insert(model1).ExecuteIdentity(); - - var t1 = g.mysql.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - - var t11 = g.mysql.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - } - - [Fact] - public void Include_OneToChilds() { - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_中国" - }; - tag1.Id = (int)g.mysql.Insert(tag1).ExecuteIdentity(); - var tag1_1 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_北京" - }; - tag1_1.Id = (int)g.mysql.Insert(tag1_1).ExecuteIdentity(); - var tag1_2 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_上海" - }; - tag1_2.Id = (int)g.mysql.Insert(tag1_2).ExecuteIdentity(); - - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_美国" - }; - tag2.Id = (int)g.mysql.Insert(tag2).ExecuteIdentity(); - var tag2_1 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_纽约" - }; - tag2_1.Id = (int)g.mysql.Insert(tag2_1).ExecuteIdentity(); - var tag2_2 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_华盛顿" - }; - tag2_2.Id = (int)g.mysql.Insert(tag2_2).ExecuteIdentity(); - - var tags0 = g.mysql.Select() - .Include(a => a.Parent) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags1 = g.mysql.Select() - .IncludeMany(a => a.Tags) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags2 = g.mysql.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags3 = g.mysql.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags11 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags22 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags33 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - } - - [Fact] - public void Include_ManyToMany() { - - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_01_中国" - }; - tag1.Id = (int)g.mysql.Insert(tag1).ExecuteIdentity(); - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_02_美国" - }; - tag2.Id = (int)g.mysql.Insert(tag2).ExecuteIdentity(); - var tag3 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_03_日本" - }; - tag3.Id = (int)g.mysql.Insert(tag3).ExecuteIdentity(); - - var song1 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_01_我是中国人.mp3", - Url = "http://ww.baidu.com/" - }; - song1.Id = (int)g.mysql.Insert(song1).ExecuteIdentity(); - var song2 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_02_爱你一万年.mp3", - Url = "http://ww.163.com/" - }; - song2.Id = (int)g.mysql.Insert(song2).ExecuteIdentity(); - var song3 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_03_千年等一回.mp3", - Url = "http://ww.sina.com/" - }; - song3.Id = (int)g.mysql.Insert(song3).ExecuteIdentity(); - - g.mysql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); - - var songs1 = g.mysql.Select() - .IncludeMany(a => a.Tags) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs1.Count); - Assert.Equal(2, songs1[0].Tags.Count); - Assert.Equal(1, songs1[1].Tags.Count); - Assert.Equal(3, songs1[2].Tags.Count); - - var songs2 = g.mysql.Select() - .IncludeMany(a => a.Tags, - then => then.IncludeMany(t => t.Songs)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs2.Count); - Assert.Equal(2, songs2[0].Tags.Count); - Assert.Equal(1, songs2[1].Tags.Count); - Assert.Equal(3, songs2[2].Tags.Count); - - var tags3 = g.mysql.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - - - var songs11 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs11.Count); - Assert.Equal(1, songs11[0].Tags.Count); - Assert.Equal(1, songs11[1].Tags.Count); - Assert.Equal(1, songs11[2].Tags.Count); - - var songs22 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.IncludeMany(t => t.Songs.Take(1))) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs22.Count); - Assert.Equal(1, songs22[0].Tags.Count); - Assert.Equal(1, songs22[1].Tags.Count); - Assert.Equal(1, songs22[2].Tags.Count); - - var tags33 = g.mysql.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs.Take(1)) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - } - } +namespace FreeSql.Tests.MySqlConnector +{ + + public class MySqlSelectTest + { + + ISelect select => g.mysql.Select(); + + [Table(Name = "tb_topic")] + public class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + [Column(OldName = "TypeGuid")] + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + + public virtual TopicFields Fields { get; set; } + } + public class TopicFields + { + [Column(IsPrimary = true)] + public int TopicId { get; set; } + public virtual Topic Topic { get; set; } + } + public class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + + public int ParentId { get; set; } + public virtual TestTypeParentInfo Parent { get; set; } + + public string Name { get; set; } + + public virtual ICollection Topics { get; set; } + } + public class TestTypeParentInfo + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + + public partial class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } + + public virtual ICollection Tags { get; set; } + } + public partial class Song_tag + { + public int Song_id { get; set; } + public virtual Song Song { get; set; } + + public int Tag_id { get; set; } + public virtual Tag Tag { get; set; } + } + public partial class Tag + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public int? Parent_id { get; set; } + public virtual Tag Parent { get; set; } + + public decimal? Ddd { get; set; } + public string Name { get; set; } + + public virtual ICollection Songs { get; set; } + public virtual ICollection Tags { get; set; } + } + + [Table(Name = "TestInfoT1", SelectFilter = " a.id > 0")] + class TestInfo + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + + [Fact] + public void AsSelect() + { + //OneToOne、ManyToOne + var t0 = g.mysql.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 + //FROM `Tag` a + //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` + //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` + //WHERE (a__Parent__Parent.`Name` = '粤语') + + //OneToMany + var t1 = g.mysql.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` + //FROM `Tag` a + //WHERE (exists(SELECT 1 + // FROM `Tag` t + // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` + // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) + // limit 0,1)) + + //ManyToMany + var t2 = g.mysql.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); + //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` + //FROM `Song` a + //WHERE(exists(SELECT 1 + // FROM `Song_tag` Mt_Ms + // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 + // FROM `Tag` t + // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) + // limit 0, 1)) + // limit 0, 1)) + } + + [Fact] + public void Lazy() + { + var tags = g.mysql.Select().Where(a => a.Parent.Name == "xxx") + .LeftJoin(a => a.Parent_id == a.Parent.Id) + .ToSql(); + + var songs = g.mysql.Select().Limit(10).ToList(); + } + + [Fact] + public void ToDataTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + + Assert.Equal(1, g.mysql.Insert().AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, g.mysql.Insert().AppendData(items).ExecuteAffrows()); + + //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + //Assert.Equal(9989, g.mysql.Insert(items).ExecuteAffrows()); + + var dt1 = select.Limit(10).ToDataTable(); + var dt2 = select.Limit(10).ToDataTable("id, 111222"); + var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); + } + + class TestDto + { + public int id { get; set; } + public string name { get; set; } //这是join表的属性 + public int ParentId { get; set; } //这是join表的属性 + } + [Fact] + public void ToList() + { + + var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto2 = select.Limit(10).ToList(a => new TestDto()); + var testDto3 = select.Limit(10).ToList(a => new TestDto { }); + var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); + var testDto5 = select.Limit(10).ToList(); + + var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); + var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); + var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); + var testDto55 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(); + + var t0 = select.Limit(50).ToList(); + + + var t1 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); + var t2 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); + + + var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToSql(); + var sql2 = select.LeftJoin((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToSql(); + var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToSql(); + + //g.mysql.Select().Join((a, b, c) => new Model.JoinResult3( + // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, + // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") + //); + + //var sql4 = select.From((a, b, c) => new SelectFrom() + // .InnerJoin(a.TypeGuid == b.Guid) + // .LeftJoin(c.Id == b.ParentId) + // .Where(b.Name == "xxx")) + //.Where(a => a.Id == 1).ToSql(); + + var sql4 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => c.Id == b.ParentId) + .Where(a => b.Name == "xxx")).ToSql(); + //.Where(a => a.Id == 1).ToSql(); + + + var list111 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => c.Id == b.ParentId) + .Where(a => b.Name != "xxx")); + var list111sql = list111.ToSql(); + var list111data = list111.ToList((a, b, c) => new + { + a.Id, + title_substring = a.Title.Substring(0, 1), + a.Type, + ccc = new { a.Id, a.Title }, + tp = a.Type, + tp2 = new + { + a.Id, + tp2 = a.Type.Name + }, + tp3 = new + { + a.Id, + tp33 = new + { + a.Id + } + } + }); + + var ttt122 = g.mysql.Select().Where(a => a.Id > 0).ToSql(); + var sql5 = g.mysql.Select().From((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToSql(); + var t11112 = g.mysql.Select().ToList(a => new + { + a.Id, + a.Title, + a.Type, + ccc = new { a.Id, a.Title }, + tp = a.Type, + tp2 = new + { + a.Id, + tp2 = a.Type.Name + }, + tp3 = new + { + a.Id, + tp33 = new + { + a.Id + } + } + + }); + + var t100 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + var t101 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + + + var t1111 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type }); + + var t2222 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type.Name }); + + g.mysql.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); + var testGuidId5 = g.mysql.Select().ToList(); + var testGuidId6 = g.mysql.Select().ToList(a => a.id); + + var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); + var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); + } + class TestGuidIdToList + { + public Guid id { get; set; } + public string title { get; set; } = Guid.NewGuid().ToString(); + } + [Fact] + public void ToOne() + { + var testnotfind = select.Where("1=2").First(a => a.CreateTime); + Assert.Equal(default(DateTime), testnotfind); + } + [Fact] + public void ToSql() + { + g.mysql.Insert().AppendData(new testenumWhere { type = testenumWhereType.Blaaa }).ExecuteAffrows(); + + var sql1 = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToSql(); + var sql2 = g.mysql.Select().Where(a => testenumWhereType.Blaaa == a.type).ToSql(); + + var sql3 = g.mysql.Select().Where(a => a.type.Equals(testenumWhereType.Blaaa)).ToSql(); + var tolist = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToList(); + } + class testenumWhere + { + public Guid id { get; set; } + public testenumWhereType type { get; set; } + } + public enum testenumWhereType { Menu, Class, Blaaa } + + [Fact] + public void Any() + { + var count = select.Where(a => 1 == 1).Count(); + Assert.False(select.Where(a => 1 == 2).Any()); + Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); + + var sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && + select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + //.Offset(a.Id) + .Any() + ).Any(c => c.Id == a.Id + 10) + ); + var sql2222Tolist = sql2222.ToList(); + + var collectionSelect = select.Where(a => + a.Type.Guid == a.TypeGuid && + a.Type.Parent.Id == a.Type.ParentId && + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) + ); + collectionSelect.ToList(); + } + [Fact] + public void Count() + { + var count = select.Where(a => 1 == 1).Count(); + select.Where(a => 1 == 1).Count(out var count2); + Assert.Equal(count, count2); + Assert.Equal(0, select.Where(a => 1 == 2).Count()); + } + [Fact] + public void Master() + { + Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); + } + [Fact] + public void From() + { + var query2 = select.From((s, b) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + ); + var sql2 = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid`", sql2); + query2.ToList(); + + var query3 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id) + ); + var sql3 = query3.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql3); + query3.ToList(); + } + [Fact] + public void LeftJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); + query.ToList(); + } + [Fact] + public void InnerJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //������� + query = select + .InnerJoin(a => a.Type.Guid == a.TypeGuid) + .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` INNER JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + query = select + .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .InnerJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` INNER JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .InnerJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` INNER JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); + query.ToList(); + + } + [Fact] + public void RightJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //������� + query = select + .RightJoin(a => a.Type.Guid == a.TypeGuid) + .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` RIGHT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + query = select + .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .RightJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` RIGHT JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .RightJoin(a => a.TypeGuid == b.Guid) + .RightJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` RIGHT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); + query.ToList(); + + } + [Fact] + public void Where() + { + + var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); + var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); + var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); + + var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.Where(a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10)", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE ((a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100))", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10) AND (a.`Clicks` > 100)", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle')", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle' AND a__Type.`Guid` = a.`TypeGuid`)", sql); + query.ToList(); + + query = select.Where(a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Name` = 'tparent')", sql); + query.ToList(); + + //���û�е������ԣ��򵥶������ + query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b WHERE (b.`Guid` = a.`TypeGuid` AND b.`Name` = 'typeTitle')", sql); + query.ToList(); + + query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b WHERE (b.`Name` = 'typeTitle' AND b.`Guid` = a.`TypeGuid`)", sql); + query.ToList(); + + query = select.Where((a, b, c) => c.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeParentInfo` c WHERE (c.`Name` = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .Where(a => a.Id == 10 && c.Name == "xxx") + .Where(a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c WHERE (a.`Id` = 10 AND c.`Name` = 'xxx') AND (b.`ParentId` = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.Where("a.clicks > 100 and a.id = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.clicks > 100 and a.id = @id)", sql); + query.ToList(); + } + [Fact] + public void WhereIf() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.WhereIf(true, a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE ((a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100))", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10) AND (a.`Clicks` > 100)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle')", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle' AND a__Type.`Guid` = a.`TypeGuid`)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Name` = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(true, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c WHERE (a.`Id` = 10 AND c.`Name` = 'xxx') AND (b.`ParentId` = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(true, "a.clicks > 100 and a.id = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.clicks > 100 and a.id = @id)", sql); + query.ToList(); + + // ==========================================WhereIf(false) + + //����е�������a.Type��a.Type.Parent ���ǵ������� + query = select.WhereIf(false, a => a.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + query2 = select.From((s, b, c) => s + .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(false, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(false, "a.clicks > 100 and a.id = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + } + [Fact] + public void WhereExists() + { + var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); + + sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + + //.Offset(a.Id) + + .Any() + ).Any() + ).ToList(); + } + [Fact] + public void GroupBy() + { + var groupby = select.From((s, b, c) => s + .Where(a => a.Id == 1) + ) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()) + .Offset(10) + .Limit(2) + .ToList(a => new + { + a.Key.tt2, + cou1 = a.Count(), + arg1 = a.Avg(a.Key.mod4), + ccc2 = a.Key.tt2 ?? "now()", + //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") + ccc3 = a.Max(a.Value.Item3.Id) + }); + + var testpid1 = g.mysql.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); + g.mysql.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); + + var aggsql1 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist1 = select + .GroupBy(a => a.Title) + .ToList(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToSql(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToList(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql3 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid), + sum3 = b.Sum(b.Value.Type.Parent.Id) + }); + } + [Fact] + public void ToAggregate() + { + var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); + } + + [Fact] + public void OrderBy() + { + var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); + } + [Fact] + public void Skip_Offset() + { + var sql = select.Offset(10).Limit(10).ToList(); + } + [Fact] + public void Take_Limit() + { + var sql = select.Limit(10).ToList(); + } + [Fact] + public void Page() + { + var sql1 = select.Page(1, 10).ToList(); + var sql2 = select.Page(2, 10).ToList(); + var sql3 = select.Page(3, 10).ToList(); + + var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); + var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); + var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); + } + [Fact] + public void Distinct() + { + var t1 = select.Distinct().ToList(a => a.Title); + var t2 = select.Distinct().Limit(10).ToList(a => a.Title); + } + + [Fact] + public void Sum() + { + } + [Fact] + public void Min() + { + } + [Fact] + public void Max() + { + } + [Fact] + public void Avg() + { + } + [Fact] + public void As() + { + } + + [Fact] + public void AsTable() + { + + var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); + + Func tableRule = (type, oldname) => + { + if (type == typeof(Topic)) return oldname + "AsTable1"; + else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; + return oldname + "AsTable"; + }; + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid`", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); + + query = select + .LeftJoin((a, b) => b.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` c ON c.`Id` = a__Type.`ParentId`", sql); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfoAsTable` c ON b.`ParentId` = c.`Id`", sql); + + //������϶����㲻�� + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); + } + + public class TestInclude_OneToManyModel1 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public virtual TestInclude_OneToManyModel2 model2 { get; set; } + + public string m1name { get; set; } + } + public class TestInclude_OneToManyModel2 + { + [Column(IsPrimary = true)] + public int model2id { get; set; } + public virtual TestInclude_OneToManyModel1 model1 { get; set; } + + public string m2setting { get; set; } + + public List childs { get; set; } + } + public class TestInclude_OneToManyModel3 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model2111Idaaa { get; set; } + public string title { get; set; } + + public List childs2 { get; set; } + } + public class TestInclude_OneToManyModel4 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model3333Id333 { get; set; } + public string title444 { get; set; } + } + + [Fact] + public void Include_OneToMany() + { + var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; + model1.id = (int)g.mysql.Insert(model1).ExecuteIdentity(); + var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; + g.mysql.Insert(model2).ExecuteAffrows(); + + var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; + model3_1.id = (int)g.mysql.Insert(model3_1).ExecuteIdentity(); + var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; + model3_2.id = (int)g.mysql.Insert(model3_2).ExecuteIdentity(); + var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; + model3_3.id = (int)g.mysql.Insert(model3_2).ExecuteIdentity(); + + var model4s = new[] { + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } + }; + Assert.Equal(5, g.mysql.Insert(model4s).ExecuteAffrows()); + + var t0 = g.mysql.Select() + .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t1 = g.mysql.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t2 = g.mysql.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + + var t00 = g.mysql.Select() + .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t11 = g.mysql.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t22 = g.mysql.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + } + + public class TestInclude_OneToManyModel11 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2id { get; set; } + public string m3setting { get; set; } + public TestInclude_OneToManyModel22 model2 { get; set; } + public string m1name { get; set; } + } + + public class TestInclude_OneToManyModel22 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public string m2setting { get; set; } + public List childs { get; set; } + } + public class TestInclude_OneToManyModel33 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2Id { get; set; } + public string title { get; set; } + public string setting { get; set; } + } + [Fact] + public void Include_OneToMany2() + { + string setting = "x"; + var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; + model2.id = (int)g.mysql.Insert(model2).ExecuteIdentity(); + + var model3s = new[] + { + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} + }; + Assert.Equal(3, g.mysql.Insert(model3s).ExecuteAffrows()); + + var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; + model1.id = (int)g.mysql.Insert(model1).ExecuteIdentity(); + + var t1 = g.mysql.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + + var t11 = g.mysql.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + } + + [Fact] + public void Include_OneToChilds() + { + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_中国" + }; + tag1.Id = (int)g.mysql.Insert(tag1).ExecuteIdentity(); + var tag1_1 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_北京" + }; + tag1_1.Id = (int)g.mysql.Insert(tag1_1).ExecuteIdentity(); + var tag1_2 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_上海" + }; + tag1_2.Id = (int)g.mysql.Insert(tag1_2).ExecuteIdentity(); + + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_美国" + }; + tag2.Id = (int)g.mysql.Insert(tag2).ExecuteIdentity(); + var tag2_1 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_纽约" + }; + tag2_1.Id = (int)g.mysql.Insert(tag2_1).ExecuteIdentity(); + var tag2_2 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_华盛顿" + }; + tag2_2.Id = (int)g.mysql.Insert(tag2_2).ExecuteIdentity(); + + var tags0 = g.mysql.Select() + .Include(a => a.Parent) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags1 = g.mysql.Select() + .IncludeMany(a => a.Tags) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags2 = g.mysql.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags3 = g.mysql.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags11 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags22 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags33 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + } + + [Fact] + public void Include_ManyToMany() + { + + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_01_中国" + }; + tag1.Id = (int)g.mysql.Insert(tag1).ExecuteIdentity(); + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_02_美国" + }; + tag2.Id = (int)g.mysql.Insert(tag2).ExecuteIdentity(); + var tag3 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_03_日本" + }; + tag3.Id = (int)g.mysql.Insert(tag3).ExecuteIdentity(); + + var song1 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_01_我是中国人.mp3", + Url = "http://ww.baidu.com/" + }; + song1.Id = (int)g.mysql.Insert(song1).ExecuteIdentity(); + var song2 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_02_爱你一万年.mp3", + Url = "http://ww.163.com/" + }; + song2.Id = (int)g.mysql.Insert(song2).ExecuteIdentity(); + var song3 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_03_千年等一回.mp3", + Url = "http://ww.sina.com/" + }; + song3.Id = (int)g.mysql.Insert(song3).ExecuteIdentity(); + + g.mysql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); + + var songs1 = g.mysql.Select() + .IncludeMany(a => a.Tags) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs1.Count); + Assert.Equal(2, songs1[0].Tags.Count); + Assert.Equal(1, songs1[1].Tags.Count); + Assert.Equal(3, songs1[2].Tags.Count); + + var songs2 = g.mysql.Select() + .IncludeMany(a => a.Tags, + then => then.IncludeMany(t => t.Songs)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs2.Count); + Assert.Equal(2, songs2[0].Tags.Count); + Assert.Equal(1, songs2[1].Tags.Count); + Assert.Equal(3, songs2[2].Tags.Count); + + var tags3 = g.mysql.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + + + var songs11 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs11.Count); + Assert.Equal(1, songs11[0].Tags.Count); + Assert.Equal(1, songs11[1].Tags.Count); + Assert.Equal(1, songs11[2].Tags.Count); + + var songs22 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.IncludeMany(t => t.Songs.Take(1))) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs22.Count); + Assert.Equal(1, songs22[0].Tags.Count); + Assert.Equal(1, songs22[1].Tags.Count); + Assert.Equal(1, songs22[2].Tags.Count); + + var tags33 = g.mysql.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs.Take(1)) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlUpdateTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlUpdateTest.cs index f8f12a20..844e7210 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlUpdateTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/Curd/MySqlUpdateTest.cs @@ -3,184 +3,199 @@ using System; using System.Collections.Generic; using Xunit; -namespace FreeSql.Tests.MySqlConnector { - public class MySqlUpdateTest { - IUpdate update => g.mysql.Update(); +namespace FreeSql.Tests.MySqlConnector +{ + public class MySqlUpdateTest + { + IUpdate update => g.mysql.Update(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestEnumUpdateTb { - [Column(IsIdentity = true)] - public int id { get; set; } - public TestEnumUpdateTbType type { get; set; } - public DateTime time { get; set; } = new DateTime(); - } - enum TestEnumUpdateTbType { str1, biggit, sum211 } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestEnumUpdateTb + { + [Column(IsIdentity = true)] + public int id { get; set; } + public TestEnumUpdateTbType type { get; set; } + public DateTime time { get; set; } = new DateTime(); + } + enum TestEnumUpdateTbType { str1, biggit, sum211 } - [Fact] - public void Dywhere() { - Assert.Null(g.mysql.Update().ToSql()); - Assert.Equal("UPDATE `tb_topic` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); - Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); - } + [Fact] + public void Dywhere() + { + Assert.Null(g.mysql.Update().ToSql()); + Assert.Equal("UPDATE `tb_topic` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); + Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); + } - [Fact] - public void SetSource() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = @p_0, `Title` = @p_1, `CreateTime` = @p_2 WHERE (`Id` = 1)", sql); + [Fact] + public void SetSource() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = @p_0, `Title` = @p_1, `CreateTime` = @p_2 WHERE (`Id` = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.SetSource(items).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = CASE `Id` WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, `Title` = CASE `Id` WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, `CreateTime` = CASE `Id` WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = CASE `Id` WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, `Title` = CASE `Id` WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, `CreateTime` = CASE `Id` WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = CASE `Id` WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = CASE `Id` WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020,1,1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `CreateTime` = @p_0 WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `CreateTime` = @p_0 WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); - Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql); - var id = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); - Assert.True(id > 0); - Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); + sql = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); + Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES(@type_0, @time_0)", sql); + var id = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); + Assert.True(id > 0); + Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); - sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0, `time` = @p_1 WHERE (`id` = 0)", sql); - g.mysql.Update().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows(); - Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); + sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0, `time` = @p_1 WHERE (`id` = 0)", sql); + g.mysql.Update().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows(); + Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); - sql = g.mysql.Insert().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); - Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); - id = g.mysql.Insert().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); - Assert.True(id > 0); - Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); + sql = g.mysql.Insert().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); + Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); + id = g.mysql.Insert().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); + Assert.True(id > 0); + Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); - sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211', `time` = '0001-01-01 00:00:00.000' WHERE (`id` = 0)", sql); - g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows(); - Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); - } - [Fact] - public void IgnoreColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211', `time` = '0001-01-01 00:00:00.000' WHERE (`id` = 0)", sql); + g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows(); + Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); + } + [Fact] + public void IgnoreColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql); - sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = 0)", sql); + sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = 0)", sql); - sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); - } - [Fact] - public void UpdateColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); + } + [Fact] + public void UpdateColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql); - sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = 0)", sql); + sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = 0)", sql); - sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); - } - [Fact] - public void Set() { - var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); + } + [Fact] + public void Set() + { + var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0 WHERE (`Id` = 1)", sql); - sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0, `CreateTime` = @p_1 WHERE (`Id` = 1)", sql); + sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = @p_0, `CreateTime` = @p_1 WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql); - int incrv = 10; - sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql); + int incrv = 10; + sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = `Clicks` * 10 / 1 WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = `Clicks` * 10 / 1 WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Id` = 10 WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Id` = 10 WHERE (`Id` = 1)", sql); - var id = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); - Assert.True(id > 0); - sql = g.mysql.Update().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", ""); - Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = {id})", sql); - g.mysql.Update().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ExecuteAffrows(); - Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); + var id = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); + Assert.True(id > 0); + sql = g.mysql.Update().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", ""); + Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = @p_0 WHERE (`id` = {id})", sql); + g.mysql.Update().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ExecuteAffrows(); + Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); - sql = g.mysql.Update().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ToSql().Replace("\r\n", ""); - Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = 'str1' WHERE (`id` = {id})", sql); - g.mysql.Update().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ExecuteAffrows(); - Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select().Where(a => a.id == id).First()?.type); - } - [Fact] - public void SetRaw() { - var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + @incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET clicks = clicks + @incrClick WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ToSql().Replace("\r\n", ""); + Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = 'str1' WHERE (`id` = {id})", sql); + g.mysql.Update().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ExecuteAffrows(); + Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select().Where(a => a.id == id).First()?.type); + } + [Fact] + public void SetRaw() + { + var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + @incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET clicks = clicks + @incrClick WHERE (`Id` = 1)", sql); - sql = g.mysql.Update().NoneParameter().Where(a => a.id == 0).SetRaw("`type` = {0}".FormatMySql(TestEnumUpdateTbType.sum211)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); - } - [Fact] - public void Where() { - var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().Where(a => a.id == 0).SetRaw("`type` = {0}".FormatMySql(TestEnumUpdateTbType.sum211)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); + } + [Fact] + public void Where() + { + var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); - sql = update.Where("id = @id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = @id)", sql); + sql = update.Where("id = @id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = @id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = g.mysql.Update().NoneParameter().Where(a => a.id == 0 && a.type == TestEnumUpdateTbType.str1) - .Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql); - } - [Fact] - public void WhereExists() { + sql = g.mysql.Update().NoneParameter().Where(a => a.id == 0 && a.type == TestEnumUpdateTbType.str1) + .Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - } - [Fact] - public void ExecuteUpdated() { + } + [Fact] + public void ExecuteUpdated() + { - } + } - [Fact] - public void AsTable() { - Assert.Null(g.mysql.Update().ToSql()); - Assert.Equal("UPDATE `tb_topicAsTable` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - } - } + [Fact] + public void AsTable() + { + Assert.Null(g.mysql.Update().ToSql()); + Assert.Equal("UPDATE `tb_topicAsTable` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/BoolNullableTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/BoolNullableTest.cs index 5202b06c..7748ad80 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/BoolNullableTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/BoolNullableTest.cs @@ -2,1561 +2,1595 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.MySqlConnectorMapType { - public class BoolNullableTest { - class BoolNullableMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool))] - public bool? tobool { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool? tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool? tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool? toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool? toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool? toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool? tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool? tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool? tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool? tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool? tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool? toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool? toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool? touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool? touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool? toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool? toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool? tostring { get; set; } = true; - } - [Fact] - public void Bool() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item = new BoolNullableMap { tobool = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item = new BoolNullableMap { tobool = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update all - item.tobool = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item.tobool = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item.tobool = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item = new BoolNullableMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item = new BoolNullableMap { tosbyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item.tosbyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item.tosbytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item = new BoolNullableMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item = new BoolNullableMap { toshort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item.toshort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item.toshortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item = new BoolNullableMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item = new BoolNullableMap { toint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item.toint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item = new BoolNullableMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item = new BoolNullableMap { tointnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item.tointnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item = new BoolNullableMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item = new BoolNullableMap { tolong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item.tolong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item.tolongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item = new BoolNullableMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item = new BoolNullableMap { tobyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item.tobyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item.tobytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item = new BoolNullableMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item = new BoolNullableMap { toushort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item.toushort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item.toushortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item = new BoolNullableMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item = new BoolNullableMap { touint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item.touint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item = new BoolNullableMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item = new BoolNullableMap { touintnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item.touintnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item = new BoolNullableMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item = new BoolNullableMap { toulong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item.toulong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item.toulongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item = new BoolNullableMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item = new BoolNullableMap { tostring = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item.tostring = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.MySqlConnectorMapType +{ + public class BoolNullableTest + { + class BoolNullableMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool))] + public bool? tobool { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool? tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool? tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool? toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool? toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool? toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool? tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool? tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool? tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool? tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool? tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool? toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool? toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool? touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool? touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool? toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool? toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool? tostring { get; set; } = true; + } + [Fact] + public void Bool() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item = new BoolNullableMap { tobool = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item = new BoolNullableMap { tobool = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update all + item.tobool = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item.tobool = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item.tobool = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item = new BoolNullableMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item = new BoolNullableMap { tosbyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item.tosbyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item.tosbytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item = new BoolNullableMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item = new BoolNullableMap { toshort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item.toshort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item.toshortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item = new BoolNullableMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item = new BoolNullableMap { toint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item.toint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item = new BoolNullableMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item = new BoolNullableMap { tointnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item.tointnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item = new BoolNullableMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item = new BoolNullableMap { tolong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item.tolong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item.tolongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item = new BoolNullableMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item = new BoolNullableMap { tobyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item.tobyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item.tobytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item = new BoolNullableMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item = new BoolNullableMap { toushort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item.toushort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item.toushortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item = new BoolNullableMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item = new BoolNullableMap { touint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item.touint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item = new BoolNullableMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item = new BoolNullableMap { touintnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item.touintnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item = new BoolNullableMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item = new BoolNullableMap { toulong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item.toulong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item.toulongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item = new BoolNullableMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item = new BoolNullableMap { tostring = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item.tostring = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/BoolTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/BoolTest.cs index f6e7bdfe..75a4ca88 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/BoolTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/BoolTest.cs @@ -2,1095 +2,1129 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.MySqlConnectorMapType { - public class BoolTest { - - class BoolMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool?))] - public bool toboolnullable { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool tostring { get; set; } = true; - } - - [Fact] - public void BoolNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item = new BoolMap { toboolnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update all - item.toboolnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item.toboolnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toboolnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toboolnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item = new BoolMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item = new BoolMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item = new BoolMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item = new BoolMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item = new BoolMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item = new BoolMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item = new BoolMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item = new BoolMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item = new BoolMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item = new BoolMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item = new BoolMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item = new BoolMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item = new BoolMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item = new BoolMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item = new BoolMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item = new BoolMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item = new BoolMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.MySqlConnectorMapType +{ + public class BoolTest + { + + class BoolMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool?))] + public bool toboolnullable { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool tostring { get; set; } = true; + } + + [Fact] + public void BoolNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item = new BoolMap { toboolnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update all + item.toboolnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item.toboolnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toboolnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toboolnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item = new BoolMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item = new BoolMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item = new BoolMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item = new BoolMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item = new BoolMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item = new BoolMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item = new BoolMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item = new BoolMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item = new BoolMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item = new BoolMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item = new BoolMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item = new BoolMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item = new BoolMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item = new BoolMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item = new BoolMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item = new BoolMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item = new BoolMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/EnumTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/EnumTest.cs index a5115406..7c3bcba2 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/EnumTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/EnumTest.cs @@ -3,252 +3,259 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.MySqlConnectorMapType { - public class EnumTest { - class EnumTestMap { - public Guid id { get; set; } +namespace FreeSql.Tests.MySqlConnectorMapType +{ + public class EnumTest + { + class EnumTestMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(int))] - public ToStringMapEnum enum_to_int { get; set; } - [Column(MapType = typeof(int?))] - public ToStringMapEnum? enumnullable_to_int { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void EnumToString() { - //insert - var orm = g.mysql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(int))] + public ToStringMapEnum enum_to_int { get; set; } + [Column(MapType = typeof(int?))] + public ToStringMapEnum? enumnullable_to_int { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void EnumToString() + { + //insert + var orm = g.mysql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToString() { - //insert - var orm = g.mysql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToString() + { + //insert + var orm = g.mysql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void EnumToInt() { - //insert - var orm = g.mysql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + [Fact] + public void EnumToInt() + { + //insert + var orm = g.mysql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //update all - item.enum_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update all + item.enum_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - item.enum_to_int = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + item.enum_to_int = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToInt() { - //insert - var orm = g.mysql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToInt() + { + //insert + var orm = g.mysql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); + item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); - //update all - item.enumnullable_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); + //update all + item.enumnullable_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); - item.enumnullable_to_int = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + item.enumnullable_to_int = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/ToStringTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/ToStringTest.cs index ae9f6796..4aadc666 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/ToStringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MapType/ToStringTest.cs @@ -3,555 +3,568 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.MySqlConnectorMapType { - public class ToStringTest { - class ToStringMap { - public Guid id { get; set; } +namespace FreeSql.Tests.MySqlConnectorMapType +{ + public class ToStringTest + { + class ToStringMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan timespan_to_string { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan? timespannullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan timespan_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan? timespannullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime datetime_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime? datetimenullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime datetime_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime? datetimenullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid guid_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid? guidnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid guid_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid? guidnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger biginteger_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger? bigintegernullable_to_string { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void Enum1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(string))] + public BigInteger biginteger_to_string { get; set; } + [Column(MapType = typeof(string))] + public BigInteger? bigintegernullable_to_string { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void Enum1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigInteger1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(0, find.biginteger_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigInteger1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(0, find.biginteger_to_string); - item = new ToStringMap { biginteger_to_string = 100 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(100, find.biginteger_to_string); + item = new ToStringMap { biginteger_to_string = 100 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(100, find.biginteger_to_string); - //update all - item.biginteger_to_string = 200; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(200, find.biginteger_to_string); + //update all + item.biginteger_to_string = 200; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(200, find.biginteger_to_string); - item.biginteger_to_string = 205; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(205, find.biginteger_to_string); + item.biginteger_to_string = 205; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(205, find.biginteger_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(522, find.biginteger_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(522, find.biginteger_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(10005, find.biginteger_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(10005, find.biginteger_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigIntegerNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigIntegerNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - item = new ToStringMap { bigintegernullable_to_string = 101 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(101, find.bigintegernullable_to_string); + item = new ToStringMap { bigintegernullable_to_string = 101 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(101, find.bigintegernullable_to_string); - //update all - item.bigintegernullable_to_string = 2004; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(2004, find.bigintegernullable_to_string); + //update all + item.bigintegernullable_to_string = 2004; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(2004, find.bigintegernullable_to_string); - item.bigintegernullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + item.bigintegernullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(998, find.bigintegernullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(998, find.bigintegernullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.bigintegernullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.bigintegernullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpan1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.Zero, find.timespan_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpan1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.Zero, find.timespan_to_string); - item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); + item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); - //update all - item.timespan_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); + //update all + item.timespan_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpanNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpanNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); + item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); - //update all - item.timespannullable_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); + //update all + item.timespannullable_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); - item.timespannullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + item.timespannullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.timespannullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.timespannullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTime1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.MinValue, find.datetime_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTime1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.MinValue, find.datetime_to_string); - item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); + item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); - //update all - item.datetime_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); + //update all + item.datetime_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTimeNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTimeNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); + item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); - //update all - item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); + //update all + item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); - item.datetimenullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + item.datetimenullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.datetimenullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.datetimenullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void Guid1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(Guid.Empty, find.guid_to_string); + [Fact] + public void Guid1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(Guid.Empty, find.guid_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guid_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guid_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update all - newid = Guid.NewGuid(); - item.guid_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + //update all + newid = Guid.NewGuid(); + item.guid_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guid_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guid_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void GuidNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void GuidNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guidnullable_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guidnullable_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - //update all - newid = Guid.NewGuid(); - item.guidnullable_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + //update all + newid = Guid.NewGuid(); + item.guidnullable_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - item.guidnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + item.guidnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guidnullable_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guidnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.guidnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.guidnullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlCodeFirstTest.cs index 6d9b8a46..48e209f0 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlCodeFirstTest.cs @@ -6,80 +6,91 @@ using System.Linq; using System.Text; using Xunit; -namespace FreeSql.Tests.MySqlConnector { - public class MySqlCodeFirstTest { +namespace FreeSql.Tests.MySqlConnector +{ + public class MySqlCodeFirstTest + { - [Fact] - public void ı_ֶ() { - var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<ı2>(); - g.mysql.CodeFirst.SyncStructure<ı2>(); + [Fact] + public void ı_ֶ() + { + var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<ı2>(); + g.mysql.CodeFirst.SyncStructure<ı2>(); - var item = new ı2 { - = "Ա", - ʱ = DateTime.Now - }; - Assert.Equal(1, g.mysql.Insert<ı2>().AppendData(item).ExecuteAffrows()); - Assert.NotEqual(Guid.Empty, item.); - var item2 = g.mysql.Select<ı2>().Where(a => a. == item.).First(); - Assert.NotNull(item2); - Assert.Equal(item., item2.); - Assert.Equal(item., item2.); - } - class ı2 { - [Column(IsPrimary = true)] - public Guid { get; set; } + var item = new ı2 + { + = "Ա", + ʱ = DateTime.Now + }; + Assert.Equal(1, g.mysql.Insert<ı2>().AppendData(item).ExecuteAffrows()); + Assert.NotEqual(Guid.Empty, item.); + var item2 = g.mysql.Select<ı2>().Where(a => a. == item.).First(); + Assert.NotNull(item2); + Assert.Equal(item., item2.); + Assert.Equal(item., item2.); + } + class ı2 + { + [Column(IsPrimary = true)] + public Guid { get; set; } - public string { get; set; } + public string { get; set; } - public DateTime ʱ { get; set; } - } + public DateTime ʱ { get; set; } + } - [Fact] - public void AddUniques() { - var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); - g.mysql.CodeFirst.SyncStructure(); - } - [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] - class AddUniquesInfo { - public Guid id { get; set; } - [Column(Unique = "uk_phone")] - public string phone { get; set; } + [Fact] + public void AddUniques() + { + var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); + g.mysql.CodeFirst.SyncStructure(); + } + [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] + class AddUniquesInfo + { + public Guid id { get; set; } + [Column(Unique = "uk_phone")] + public string phone { get; set; } - [Column(Unique = "uk_group_index, uk_group_index22")] - public string group { get; set; } - [Column(Unique = "uk_group_index")] - public int index { get; set; } - [Column(Unique = "uk_group_index22")] - public string index22 { get; set; } - } + [Column(Unique = "uk_group_index, uk_group_index22")] + public string group { get; set; } + [Column(Unique = "uk_group_index")] + public int index { get; set; } + [Column(Unique = "uk_group_index22")] + public string index22 { get; set; } + } - [Fact] - public void AddField() { - var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); + [Fact] + public void AddField() + { + var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); - var id = g.mysql.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); - } + var id = g.mysql.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); + } - [Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")] - public class TopicAddField { - [Column(IsIdentity = true)] - public int? Id { get; set; } + [Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")] + public class TopicAddField + { + [Column(IsIdentity = true)] + public int? Id { get; set; } - public string name { get; set; } + public string name { get; set; } - [Column(DbType = "varchar(200) not null", OldName = "title")] - public string title222 { get; set; } = "10"; + [Column(DbType = "varchar(200) not null", OldName = "title")] + public string title222 { get; set; } = "10"; - [Column(IsIgnore = true)] - public DateTime ct { get; set; } = DateTime.Now; - } + [Column(IsIgnore = true)] + public DateTime ct { get; set; } = DateTime.Now; + } - [Fact] - public void GetComparisonDDLStatements() { + [Fact] + public void GetComparisonDDLStatements() + { - var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); - if (string.IsNullOrEmpty(sql) == false) { - Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` ( + var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); + if (string.IsNullOrEmpty(sql) == false) + { + Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` ( `Id` INT(11) NOT NULL AUTO_INCREMENT, `testFieldBool` BIT(1) NOT NULL, `testFieldSByte` TINYINT(3) NOT NULL, @@ -126,352 +137,363 @@ namespace FreeSql.Tests.MySqlConnector { PRIMARY KEY (`Id`) ) Engine=InnoDB; ", sql); - } - - sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); - } - - IInsert insert => g.mysql.Insert(); - ISelect select => g.mysql.Select(); - - [Fact] - public void CurdAllField() { - var item = new TableAllType { }; - item.Id = (int)insert.AppendData(item).ExecuteIdentity(); - - var newitem = select.Where(a => a.Id == item.Id).ToOne(); - - var item2 = new TableAllType { - testFieldBool = true, - testFieldBoolNullable = true, - testFieldByte = 255, - testFieldByteNullable = 127, - testFieldBytes = Encoding.UTF8.GetBytes("й"), - testFieldDateTime = DateTime.Now, - testFieldDateTimeNullable = DateTime.Now.AddHours(-1), - testFieldDecimal = 99.99M, - testFieldDecimalNullable = 99.98M, - testFieldDouble = 999.99, - testFieldDoubleNullable = 999.98, - testFieldEnum1 = TableAllTypeEnumType1.e5, - testFieldEnum1Nullable = TableAllTypeEnumType1.e3, - testFieldEnum2 = TableAllTypeEnumType2.f2, - testFieldEnum2Nullable = TableAllTypeEnumType2.f3, - testFieldFloat = 19.99F, - testFieldFloatNullable = 19.98F, - testFieldGuid = Guid.NewGuid(), - testFieldGuidNullable = Guid.NewGuid(), - testFieldInt = int.MaxValue, - testFieldIntNullable = int.MinValue, - testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }), - testFieldLong = long.MaxValue, - testFieldMultiLineString = new MygisMultiLineString(new[] { - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }, - new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }), - testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }), - testFieldMultiPolygon = new MygisMultiPolygon(new[] { - new MygisPolygon(new[] { - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }), - new MygisPolygon(new[] { - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }), - testFieldPoint = new MygisPoint(99, 99), - testFieldPolygon = new MygisPolygon(new[] { - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }), - testFieldSByte = 100, - testFieldSByteNullable = 99, - testFieldShort = short.MaxValue, - testFieldShortNullable = short.MinValue, - testFieldString = "йstring", - testFieldTimeSpan = TimeSpan.FromSeconds(999), - testFieldTimeSpanNullable = TimeSpan.FromSeconds(60), - testFieldUInt = uint.MaxValue, - testFieldUIntNullable = uint.MinValue, - testFieldULong = ulong.MaxValue, - testFieldULongNullable = ulong.MinValue, - testFieldUShort = ushort.MaxValue, - testFieldUShortNullable = ushort.MinValue, - testFielLongNullable = long.MinValue - }; - item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); - var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); + } + + sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); + } + + IInsert insert => g.mysql.Insert(); + ISelect select => g.mysql.Select(); + + [Fact] + public void CurdAllField() + { + var item = new TableAllType { }; + item.Id = (int)insert.AppendData(item).ExecuteIdentity(); + + var newitem = select.Where(a => a.Id == item.Id).ToOne(); + + var item2 = new TableAllType + { + testFieldBool = true, + testFieldBoolNullable = true, + testFieldByte = 255, + testFieldByteNullable = 127, + testFieldBytes = Encoding.UTF8.GetBytes("й"), + testFieldDateTime = DateTime.Now, + testFieldDateTimeNullable = DateTime.Now.AddHours(-1), + testFieldDecimal = 99.99M, + testFieldDecimalNullable = 99.98M, + testFieldDouble = 999.99, + testFieldDoubleNullable = 999.98, + testFieldEnum1 = TableAllTypeEnumType1.e5, + testFieldEnum1Nullable = TableAllTypeEnumType1.e3, + testFieldEnum2 = TableAllTypeEnumType2.f2, + testFieldEnum2Nullable = TableAllTypeEnumType2.f3, + testFieldFloat = 19.99F, + testFieldFloatNullable = 19.98F, + testFieldGuid = Guid.NewGuid(), + testFieldGuidNullable = Guid.NewGuid(), + testFieldInt = int.MaxValue, + testFieldIntNullable = int.MinValue, + testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }), + testFieldLong = long.MaxValue, + testFieldMultiLineString = new MygisMultiLineString(new[] { + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }, + new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }), + testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }), + testFieldMultiPolygon = new MygisMultiPolygon(new[] { + new MygisPolygon(new[] { + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }), + new MygisPolygon(new[] { + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }), + testFieldPoint = new MygisPoint(99, 99), + testFieldPolygon = new MygisPolygon(new[] { + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }), + testFieldSByte = 100, + testFieldSByteNullable = 99, + testFieldShort = short.MaxValue, + testFieldShortNullable = short.MinValue, + testFieldString = "йstring", + testFieldTimeSpan = TimeSpan.FromSeconds(999), + testFieldTimeSpanNullable = TimeSpan.FromSeconds(60), + testFieldUInt = uint.MaxValue, + testFieldUIntNullable = uint.MinValue, + testFieldULong = ulong.MaxValue, + testFieldULongNullable = ulong.MinValue, + testFieldUShort = ushort.MaxValue, + testFieldUShortNullable = ushort.MinValue, + testFielLongNullable = long.MinValue + }; + item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); + var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); - var items = select.ToList(); - } + var items = select.ToList(); + } - [JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")] - public partial class Tb_alltype { + [JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")] + public partial class Tb_alltype + { - [JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)] - public int Id { get; set; } + [JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)] + public int Id { get; set; } - [JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")] - public bool TestFieldBool { get; set; } + [JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")] + public bool TestFieldBool { get; set; } - [JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)] - public bool? TestFieldBoolNullable { get; set; } + [JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)] + public bool? TestFieldBoolNullable { get; set; } - [JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")] - public byte TestFieldByte { get; set; } + [JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")] + public byte TestFieldByte { get; set; } - [JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)] - public byte? TestFieldByteNullable { get; set; } + [JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)] + public byte? TestFieldByteNullable { get; set; } - [JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)] - public byte[] TestFieldBytes { get; set; } + [JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)] + public byte[] TestFieldBytes { get; set; } - [JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")] - public DateTime TestFieldDateTime { get; set; } + [JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")] + public DateTime TestFieldDateTime { get; set; } - [JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)] - public DateTime? TestFieldDateTimeNullable { get; set; } + [JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)] + public DateTime? TestFieldDateTimeNullable { get; set; } - [JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")] - public decimal TestFieldDecimal { get; set; } + [JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")] + public decimal TestFieldDecimal { get; set; } - [JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)] - public decimal? TestFieldDecimalNullable { get; set; } + [JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)] + public decimal? TestFieldDecimalNullable { get; set; } - [JsonProperty, Column(Name = "testFieldDouble", DbType = "double")] - public double TestFieldDouble { get; set; } + [JsonProperty, Column(Name = "testFieldDouble", DbType = "double")] + public double TestFieldDouble { get; set; } - [JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)] - public double? TestFieldDoubleNullable { get; set; } + [JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)] + public double? TestFieldDoubleNullable { get; set; } - [JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")] - public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; } + [JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")] + public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; } - [JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)] - public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; } + [JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)] + public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; } - [JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")] - public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; } + [JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")] + public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; } - [JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)] - public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; } + [JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)] + public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; } - [JsonProperty, Column(Name = "testFieldFloat", DbType = "float")] - public float TestFieldFloat { get; set; } + [JsonProperty, Column(Name = "testFieldFloat", DbType = "float")] + public float TestFieldFloat { get; set; } - [JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)] - public float? TestFieldFloatNullable { get; set; } + [JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)] + public float? TestFieldFloatNullable { get; set; } - [JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")] - public Guid TestFieldGuid { get; set; } + [JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")] + public Guid TestFieldGuid { get; set; } - [JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)] - public Guid? TestFieldGuidNullable { get; set; } + [JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)] + public Guid? TestFieldGuidNullable { get; set; } - [JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")] - public int TestFieldInt { get; set; } + [JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")] + public int TestFieldInt { get; set; } - [JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)] - public int? TestFieldIntNullable { get; set; } + [JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)] + public int? TestFieldIntNullable { get; set; } - [JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)] - public MygisGeometry TestFieldLineString { get; set; } + [JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)] + public MygisGeometry TestFieldLineString { get; set; } - [JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")] - public long TestFieldLong { get; set; } + [JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")] + public long TestFieldLong { get; set; } - [JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)] - public MygisGeometry TestFieldMultiLineString { get; set; } + [JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)] + public MygisGeometry TestFieldMultiLineString { get; set; } - [JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)] - public MygisGeometry TestFieldMultiPoint { get; set; } + [JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)] + public MygisGeometry TestFieldMultiPoint { get; set; } - [JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)] - public MygisGeometry TestFieldMultiPolygon { get; set; } + [JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)] + public MygisGeometry TestFieldMultiPolygon { get; set; } - [JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)] - public MygisGeometry TestFieldPoint { get; set; } + [JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)] + public MygisGeometry TestFieldPoint { get; set; } - [JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)] - public MygisGeometry TestFieldPolygon { get; set; } + [JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)] + public MygisGeometry TestFieldPolygon { get; set; } - [JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")] - public sbyte TestFieldSByte { get; set; } + [JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")] + public sbyte TestFieldSByte { get; set; } - [JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)] - public sbyte? TestFieldSByteNullable { get; set; } + [JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)] + public sbyte? TestFieldSByteNullable { get; set; } - [JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")] - public short TestFieldShort { get; set; } + [JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")] + public short TestFieldShort { get; set; } - [JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)] - public short? TestFieldShortNullable { get; set; } + [JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)] + public short? TestFieldShortNullable { get; set; } - [JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)] - public string TestFieldString { get; set; } + [JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)] + public string TestFieldString { get; set; } - [JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")] - public TimeSpan TestFieldTimeSpan { get; set; } + [JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")] + public TimeSpan TestFieldTimeSpan { get; set; } - [JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)] - public TimeSpan? TestFieldTimeSpanNullable { get; set; } + [JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)] + public TimeSpan? TestFieldTimeSpanNullable { get; set; } - [JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")] - public uint TestFieldUInt { get; set; } + [JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")] + public uint TestFieldUInt { get; set; } - [JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)] - public uint? TestFieldUIntNullable { get; set; } + [JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)] + public uint? TestFieldUIntNullable { get; set; } - [JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")] - public ulong TestFieldULong { get; set; } + [JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")] + public ulong TestFieldULong { get; set; } - [JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)] - public ulong? TestFieldULongNullable { get; set; } + [JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)] + public ulong? TestFieldULongNullable { get; set; } - [JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")] - public ushort TestFieldUShort { get; set; } + [JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")] + public ushort TestFieldUShort { get; set; } - [JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)] - public ushort? TestFieldUShortNullable { get; set; } + [JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)] + public ushort? TestFieldUShortNullable { get; set; } - [JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)] - public long? TestFielLongNullable { get; set; } + [JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)] + public long? TestFielLongNullable { get; set; } - internal static IFreeSql mysql => null; - public static FreeSql.ISelect Select => mysql.Select(); + internal static IFreeSql mysql => null; + public static FreeSql.ISelect Select => mysql.Select(); - public static long Delete(int Id) { - var affrows = mysql.Delete().Where(a => a.Id == Id).ExecuteAffrows(); - return affrows; - } + public static long Delete(int Id) + { + var affrows = mysql.Delete().Where(a => a.Id == Id).ExecuteAffrows(); + return affrows; + } - /// - /// ӣֵ UpdateӰΪ 0 Insert - /// - public void Save() { - if (this.Id != default(int)) { - var affrows = mysql.Update().Where(a => a.Id == Id).ExecuteAffrows(); - if (affrows > 0) return; - } - this.Id = (int)mysql.Insert().AppendData(this).ExecuteIdentity(); - } + /// + /// ӣֵ UpdateӰΪ 0 Insert + /// + public void Save() + { + if (this.Id != default(int)) + { + var affrows = mysql.Update().Where(a => a.Id == Id).ExecuteAffrows(); + if (affrows > 0) return; + } + this.Id = (int)mysql.Insert().AppendData(this).ExecuteIdentity(); + } - } + } - public enum Tb_alltypeTESTFIELDENUM1 { - E1 = 1, E2, E3, E5 - } - public enum Tb_alltypeTESTFIELDENUM1NULLABLE { - E1 = 1, E2, E3, E5 - } - [Flags] - public enum Tb_alltypeTESTFIELDENUM2 : long { - F1 = 1, F2 = 2, F3 = 4 - } - [Flags] - public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long { - F1 = 1, F2 = 2, F3 = 4 - } + public enum Tb_alltypeTESTFIELDENUM1 + { + E1 = 1, E2, E3, E5 + } + public enum Tb_alltypeTESTFIELDENUM1NULLABLE + { + E1 = 1, E2, E3, E5 + } + [Flags] + public enum Tb_alltypeTESTFIELDENUM2 : long + { + F1 = 1, F2 = 2, F3 = 4 + } + [Flags] + public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long + { + F1 = 1, F2 = 2, F3 = 4 + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - - public bool testFieldBool { get; set; } - public sbyte testFieldSByte { get; set; } - public short testFieldShort { get; set; } - public int testFieldInt { get; set; } - public long testFieldLong { get; set; } - public byte testFieldByte { get; set; } - public ushort testFieldUShort { get; set; } - public uint testFieldUInt { get; set; } - public ulong testFieldULong { get; set; } - public double testFieldDouble { get; set; } - public float testFieldFloat { get; set; } - public decimal testFieldDecimal { get; set; } - public TimeSpan testFieldTimeSpan { get; set; } - public DateTime testFieldDateTime { get; set; } - public byte[] testFieldBytes { get; set; } - public string testFieldString { get; set; } - public Guid testFieldGuid { get; set; } - - public bool? testFieldBoolNullable { get; set; } - public sbyte? testFieldSByteNullable { get; set; } - public short? testFieldShortNullable { get; set; } - public int? testFieldIntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? testFieldByteNullable { get; set; } - public ushort? testFieldUShortNullable { get; set; } - public uint? testFieldUIntNullable { get; set; } - public ulong? testFieldULongNullable { get; set; } - public double? testFieldDoubleNullable { get; set; } - public float? testFieldFloatNullable { get; set; } - public decimal? testFieldDecimalNullable { get; set; } - public TimeSpan? testFieldTimeSpanNullable { get; set; } - public DateTime? testFieldDateTimeNullable { get; set; } - public Guid? testFieldGuidNullable { get; set; } - - public MygisPoint testFieldPoint { get; set; } - public MygisLineString testFieldLineString { get; set; } - public MygisPolygon testFieldPolygon { get; set; } - public MygisMultiPoint testFieldMultiPoint { get; set; } - public MygisMultiLineString testFieldMultiLineString { get; set; } - public MygisMultiPolygon testFieldMultiPolygon { get; set; } - - public TableAllTypeEnumType1 testFieldEnum1 { get; set; } - public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } - public TableAllTypeEnumType2 testFieldEnum2 { get; set; } - public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } - } - - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + + public bool testFieldBool { get; set; } + public sbyte testFieldSByte { get; set; } + public short testFieldShort { get; set; } + public int testFieldInt { get; set; } + public long testFieldLong { get; set; } + public byte testFieldByte { get; set; } + public ushort testFieldUShort { get; set; } + public uint testFieldUInt { get; set; } + public ulong testFieldULong { get; set; } + public double testFieldDouble { get; set; } + public float testFieldFloat { get; set; } + public decimal testFieldDecimal { get; set; } + public TimeSpan testFieldTimeSpan { get; set; } + public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } + public string testFieldString { get; set; } + public Guid testFieldGuid { get; set; } + + public bool? testFieldBoolNullable { get; set; } + public sbyte? testFieldSByteNullable { get; set; } + public short? testFieldShortNullable { get; set; } + public int? testFieldIntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? testFieldByteNullable { get; set; } + public ushort? testFieldUShortNullable { get; set; } + public uint? testFieldUIntNullable { get; set; } + public ulong? testFieldULongNullable { get; set; } + public double? testFieldDoubleNullable { get; set; } + public float? testFieldFloatNullable { get; set; } + public decimal? testFieldDecimalNullable { get; set; } + public TimeSpan? testFieldTimeSpanNullable { get; set; } + public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } + + public MygisPoint testFieldPoint { get; set; } + public MygisLineString testFieldLineString { get; set; } + public MygisPolygon testFieldPolygon { get; set; } + public MygisMultiPoint testFieldMultiPoint { get; set; } + public MygisMultiLineString testFieldMultiLineString { get; set; } + public MygisMultiPolygon testFieldMultiPolygon { get; set; } + + public TableAllTypeEnumType1 testFieldEnum1 { get; set; } + public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } + public TableAllTypeEnumType2 testFieldEnum2 { get; set; } + public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } + } + + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorAdo/MySqlAdoTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorAdo/MySqlAdoTest.cs index e2ec87e4..f1d59702 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorAdo/MySqlAdoTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorAdo/MySqlAdoTest.cs @@ -2,53 +2,64 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.MySqlConnector { - public class MySqlAdoTest { - [Fact] - public void Pool() { - var t1 = g.mysql.Ado.MasterPool.StatisticsFullily; - } +namespace FreeSql.Tests.MySqlConnector +{ + public class MySqlAdoTest + { + [Fact] + public void Pool() + { + var t1 = g.mysql.Ado.MasterPool.StatisticsFullily; + } - [Fact] - public void SlavePools() { - var t2 = g.mysql.Ado.SlavePools.Count; - } + [Fact] + public void SlavePools() + { + var t2 = g.mysql.Ado.SlavePools.Count; + } - [Fact] - public void ExecuteReader() { - - } - [Fact] - public void ExecuteArray() { - - } - [Fact] - public void ExecuteNonQuery() { - - } - [Fact] - public void ExecuteScalar() { - - } + [Fact] + public void ExecuteReader() + { - [Fact] - public void Query() { - var t3 = g.mysql.Ado.Query("select * from song"); + } + [Fact] + public void ExecuteArray() + { - var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song"); + } + [Fact] + public void ExecuteNonQuery() + { - var t5 = g.mysql.Ado.Query("select * from song"); - } + } + [Fact] + public void ExecuteScalar() + { - [Fact] - public void QueryMultipline() { - var t3 = g.mysql.Ado.Query("select * from song; select * from song; select * from song"); - } + } - class xxx { - public int Id { get; set; } - public string Path { get; set; } - public string Title2 { get; set; } - } - } + [Fact] + public void Query() + { + var t3 = g.mysql.Ado.Query("select * from song"); + + var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song"); + + var t5 = g.mysql.Ado.Query("select * from song"); + } + + [Fact] + public void QueryMultipline() + { + var t3 = g.mysql.Ado.Query("select * from song; select * from song; select * from song"); + } + + class xxx + { + public int Id { get; set; } + public string Path { get; set; } + public string Title2 { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/ConvertTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/ConvertTest.cs index 8aff8e08..4fdc2304 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/ConvertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/ConvertTest.cs @@ -4,143 +4,166 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnectorExpression { - public class ConvertTest { +namespace FreeSql.Tests.MySqlConnectorExpression +{ + public class ConvertTest + { - ISelect select => g.mysql.Select(); + ISelect select => g.mysql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void ToBoolean() { - var data = new List(); - data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); - data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); - } - [Fact] - public void ToByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); - data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); - } - [Fact] - public void ToChar() { - var data = new List(); - data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); - data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); - } - [Fact] - public void ToDateTime() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); - } - [Fact] - public void ToDecimal() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToDouble() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt32() { - var data = new List(); - data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); - data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToSByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); - data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); - } - [Fact] - public void ToSingle() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); - data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); - } - [Fact] - public void ToUInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt32() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); - } + [Fact] + public void ToBoolean() + { + var data = new List(); + data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); + data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); + } + [Fact] + public void ToByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); + data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); + } + [Fact] + public void ToChar() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); + data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); + } + [Fact] + public void ToDateTime() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); + } + [Fact] + public void ToDecimal() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToDouble() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt32() + { + var data = new List(); + data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); + data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToSByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); + data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); + } + [Fact] + public void ToSingle() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); + data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); + } + [Fact] + public void ToUInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt32() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); + } - [Fact] - public void Guid_Parse() { - var data = new List(); - data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); - } + [Fact] + public void Guid_Parse() + { + var data = new List(); + data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); + } - [Fact] - public void Guid_NewGuid() { - var data = new List(); - //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); - } + [Fact] + public void Guid_NewGuid() + { + var data = new List(); + //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); + } - [Fact] - public void Random() { - var data = new List(); - data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); - data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); - } - } + [Fact] + public void Random() + { + var data = new List(); + data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); + data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/DateTimeTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/DateTimeTest.cs index 5dcbc74b..fbb5e47b 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/DateTimeTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/DateTimeTest.cs @@ -4,620 +4,658 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnectorExpression { - public class DateTimeTest { - - ISelect select => g.mysql.Select(); - - [Table(Name = "tb_topic111333")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - [Table(Name = "TestTypeInfo333")] - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - public DateTime Time { get; set; } - } - [Table(Name = "TestTypeParentInfo23123")] - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - public DateTime Time2 { get; set; } - } - [Fact] - public void Now() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void UtcNow() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void Date() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) - } - [Fact] - public void TimeOfDay() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) - } - [Fact] - public void DayOfWeek() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) - } - [Fact] - public void Day() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) - } - [Fact] - public void DayOfYear() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) - } - [Fact] - public void Month() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (month(a.`CreateTime`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (month(a__Type.`Time`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (month(a__Type__Parent.`Time2`) > month(now())) - } - [Fact] - public void Year() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (year(a.`CreateTime`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (year(a__Type.`Time`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (year(a__Type__Parent.`Time2`) > year(now())) - } - [Fact] - public void Hour() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (hour(a.`CreateTime`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (hour(a__Type.`Time`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) - } - [Fact] - public void Minute() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (minute(a.`CreateTime`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (minute(a__Type.`Time`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) - } - [Fact] - public void Second() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (second(a.`CreateTime`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (second(a__Type.`Time`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (second(a__Type__Parent.`Time2`) > second(now())) - } - [Fact] - public void Millisecond() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) - } - [Fact] - public void AddDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) - } - [Fact] - public void AddHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) - } - [Fact] - public void AddMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) - } - [Fact] - public void AddMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) - } - [Fact] - public void AddMonths() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) - } - [Fact] - public void AddSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) - } - [Fact] - public void AddTicks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) - } - [Fact] - public void AddYears() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((timestampdiff(microsecond, now(), a.`CreateTime`)) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((timestampdiff(microsecond, now(), a__Type.`Time`)) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((timestampdiff(microsecond, now(), a__Type__Parent.`Time2`)) / 1000000) > 0); - data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_sub(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_sub(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_sub(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`) - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) - } - - [Fact] - public void DateTime_Compare() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((a.`CreateTime`) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) - } - [Fact] - public void DateTime_DaysInMonth() { - var data = new List(); - data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) - } - [Fact] - public void DateTime_Equals() { - var data = new List(); - data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void DateTime_IsLeapYear() { - var data = new List(); - data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) - } - [Fact] - public void DateTime_Parse() { - var data = new List(); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) - } - } +namespace FreeSql.Tests.MySqlConnectorExpression +{ + public class DateTimeTest + { + + ISelect select => g.mysql.Select(); + + [Table(Name = "tb_topic111333")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + [Table(Name = "TestTypeInfo333")] + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + public DateTime Time { get; set; } + } + [Table(Name = "TestTypeParentInfo23123")] + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + public DateTime Time2 { get; set; } + } + [Fact] + public void Now() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void UtcNow() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void Date() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) + } + [Fact] + public void TimeOfDay() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) + } + [Fact] + public void DayOfWeek() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) + } + [Fact] + public void Day() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) + } + [Fact] + public void DayOfYear() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) + } + [Fact] + public void Month() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (month(a.`CreateTime`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (month(a__Type.`Time`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (month(a__Type__Parent.`Time2`) > month(now())) + } + [Fact] + public void Year() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (year(a.`CreateTime`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (year(a__Type.`Time`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (year(a__Type__Parent.`Time2`) > year(now())) + } + [Fact] + public void Hour() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (hour(a.`CreateTime`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (hour(a__Type.`Time`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) + } + [Fact] + public void Minute() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (minute(a.`CreateTime`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (minute(a__Type.`Time`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) + } + [Fact] + public void Second() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (second(a.`CreateTime`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (second(a__Type.`Time`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (second(a__Type__Parent.`Time2`) > second(now())) + } + [Fact] + public void Millisecond() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) + } + [Fact] + public void AddDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) + } + [Fact] + public void AddHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) + } + [Fact] + public void AddMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) + } + [Fact] + public void AddMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) + } + [Fact] + public void AddMonths() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) + } + [Fact] + public void AddSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) + } + [Fact] + public void AddTicks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) + } + [Fact] + public void AddYears() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((timestampdiff(microsecond, now(), a.`CreateTime`)) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((timestampdiff(microsecond, now(), a__Type.`Time`)) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((timestampdiff(microsecond, now(), a__Type__Parent.`Time2`)) / 1000000) > 0); + data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_sub(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_sub(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_sub(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`) + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) + } + + [Fact] + public void DateTime_Compare() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((a.`CreateTime`) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) + } + [Fact] + public void DateTime_DaysInMonth() + { + var data = new List(); + data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) + } + [Fact] + public void DateTime_Equals() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void DateTime_IsLeapYear() + { + var data = new List(); + data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) + } + [Fact] + public void DateTime_Parse() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/MathTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/MathTest.cs index 83d333b5..7a70825a 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/MathTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/MathTest.cs @@ -4,129 +4,153 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnectorExpression { - public class MathTest { +namespace FreeSql.Tests.MySqlConnectorExpression +{ + public class MathTest + { - ISelect select => g.mysql.Select(); + ISelect select => g.mysql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void PI() { - var data = new List(); - data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); - } - [Fact] - public void Abs() { - var data = new List(); - data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Sign() { - var data = new List(); - data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Floor() { - var data = new List(); - data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); - } - [Fact] - public void Ceiling() { - var data = new List(); - data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Round() { - var data = new List(); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); - } - [Fact] - public void Exp() { - var data = new List(); - data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log() { - var data = new List(); - data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log10() { - var data = new List(); - data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Pow() { - var data = new List(); - data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sqrt() { - var data = new List(); - data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Cos() { - var data = new List(); - data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sin() { - var data = new List(); - data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Tan() { - var data = new List(); - data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Acos() { - var data = new List(); - data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Asin() { - var data = new List(); - data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan() { - var data = new List(); - data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan2() { - var data = new List(); - data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Truncate() { - var data = new List(); - data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); - } - } + [Fact] + public void PI() + { + var data = new List(); + data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); + } + [Fact] + public void Abs() + { + var data = new List(); + data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Sign() + { + var data = new List(); + data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Floor() + { + var data = new List(); + data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); + } + [Fact] + public void Ceiling() + { + var data = new List(); + data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Round() + { + var data = new List(); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); + } + [Fact] + public void Exp() + { + var data = new List(); + data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log() + { + var data = new List(); + data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log10() + { + var data = new List(); + data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Pow() + { + var data = new List(); + data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sqrt() + { + var data = new List(); + data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Cos() + { + var data = new List(); + data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sin() + { + var data = new List(); + data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Tan() + { + var data = new List(); + data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Acos() + { + var data = new List(); + data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Asin() + { + var data = new List(); + data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan() + { + var data = new List(); + data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan2() + { + var data = new List(); + data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Truncate() + { + var data = new List(); + data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/OtherTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/OtherTest.cs index ad037e00..8fc9d3eb 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/OtherTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/OtherTest.cs @@ -5,117 +5,123 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnectorExpression { - public class OtherTest { +namespace FreeSql.Tests.MySqlConnectorExpression +{ + public class OtherTest + { - ISelect select => g.mysql.Select(); + ISelect select => g.mysql.Select(); - public OtherTest() { - - } + public OtherTest() + { - [Fact] - public void Boolean() { - var t1 = select.Where(a => a.testFieldBool == true).ToList(); - var t2 = select.Where(a => a.testFieldBool != true).ToList(); - var t3 = select.Where(a => a.testFieldBool == false).ToList(); - var t4 = select.Where(a => !a.testFieldBool).ToList(); - var t5 = select.Where(a => a.testFieldBool).ToList(); + } - var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList(); - var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); - var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); - var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); - var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList(); - } + [Fact] + public void Boolean() + { + var t1 = select.Where(a => a.testFieldBool == true).ToList(); + var t2 = select.Where(a => a.testFieldBool != true).ToList(); + var t3 = select.Where(a => a.testFieldBool == false).ToList(); + var t4 = select.Where(a => !a.testFieldBool).ToList(); + var t5 = select.Where(a => a.testFieldBool).ToList(); - [Fact] - public void Array() { - int[] nullarr = null; - Assert.Throws(() => { select.Where(a => nullarr.Contains(a.testFieldInt)).ToList(); }); - Assert.Throws(() => { select.Where(a => new int[0].Contains(a.testFieldInt)).ToList(); }); + var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList(); + var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); + var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); + var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); + var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList(); + } - IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); - var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); + [Fact] + public void Array() + { + int[] nullarr = null; + Assert.Throws(() => { select.Where(a => nullarr.Contains(a.testFieldInt)).ToList(); }); + Assert.Throws(() => { select.Where(a => new int[0].Contains(a.testFieldInt)).ToList(); }); - //in not in - var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); - var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); + var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); - var inarray = new[] { 1, 2, 3 }; - var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); - var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); - var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); + //in not in + var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); + var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - //in not in - var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); - var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var inarray = new[] { 1, 2, 3 }; + var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); + var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); + var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); - var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); - var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); - var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); + //in not in + var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); + var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var inarray2 = new List() { 1, 2, 3 }; - var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); - var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); - var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); - } + var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); + var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); + var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + var inarray2 = new List() { 1, 2, 3 }; + var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); + var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); + var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); + } - public bool testFieldBool { get; set; } - public sbyte testFieldSByte { get; set; } - public short testFieldShort { get; set; } - public int testFieldInt { get; set; } - public long testFieldLong { get; set; } - public byte testFieldByte { get; set; } - public ushort testFieldUShort { get; set; } - public uint testFieldUInt { get; set; } - public ulong testFieldULong { get; set; } - public double testFieldDouble { get; set; } - public float testFieldFloat { get; set; } - public decimal testFieldDecimal { get; set; } - public TimeSpan testFieldTimeSpan { get; set; } - public DateTime testFieldDateTime { get; set; } - public byte[] testFieldBytes { get; set; } - public string testFieldString { get; set; } - public Guid testFieldGuid { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - public bool? testFieldBoolNullable { get; set; } - public sbyte? testFieldSByteNullable { get; set; } - public short? testFieldShortNullable { get; set; } - public int? testFieldIntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? testFieldByteNullable { get; set; } - public ushort? testFieldUShortNullable { get; set; } - public uint? testFieldUIntNullable { get; set; } - public ulong? testFieldULongNullable { get; set; } - public double? testFieldDoubleNullable { get; set; } - public float? testFieldFloatNullable { get; set; } - public decimal? testFieldDecimalNullable { get; set; } - public TimeSpan? testFieldTimeSpanNullable { get; set; } - public DateTime? testFieldDateTimeNullable { get; set; } - public Guid? testFieldGuidNullable { get; set; } + public bool testFieldBool { get; set; } + public sbyte testFieldSByte { get; set; } + public short testFieldShort { get; set; } + public int testFieldInt { get; set; } + public long testFieldLong { get; set; } + public byte testFieldByte { get; set; } + public ushort testFieldUShort { get; set; } + public uint testFieldUInt { get; set; } + public ulong testFieldULong { get; set; } + public double testFieldDouble { get; set; } + public float testFieldFloat { get; set; } + public decimal testFieldDecimal { get; set; } + public TimeSpan testFieldTimeSpan { get; set; } + public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } + public string testFieldString { get; set; } + public Guid testFieldGuid { get; set; } - public MygisPoint testFieldPoint { get; set; } - public MygisLineString testFieldLineString { get; set; } - public MygisPolygon testFieldPolygon { get; set; } - public MygisMultiPoint testFieldMultiPoint { get; set; } - public MygisMultiLineString testFieldMultiLineString { get; set; } - public MygisMultiPolygon testFieldMultiPolygon { get; set; } + public bool? testFieldBoolNullable { get; set; } + public sbyte? testFieldSByteNullable { get; set; } + public short? testFieldShortNullable { get; set; } + public int? testFieldIntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? testFieldByteNullable { get; set; } + public ushort? testFieldUShortNullable { get; set; } + public uint? testFieldUIntNullable { get; set; } + public ulong? testFieldULongNullable { get; set; } + public double? testFieldDoubleNullable { get; set; } + public float? testFieldFloatNullable { get; set; } + public decimal? testFieldDecimalNullable { get; set; } + public TimeSpan? testFieldTimeSpanNullable { get; set; } + public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } - public TableAllTypeEnumType1 testFieldEnum1 { get; set; } - public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } - public TableAllTypeEnumType2 testFieldEnum2 { get; set; } - public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } - } + public MygisPoint testFieldPoint { get; set; } + public MygisLineString testFieldLineString { get; set; } + public MygisPolygon testFieldPolygon { get; set; } + public MygisMultiPoint testFieldMultiPoint { get; set; } + public MygisMultiLineString testFieldMultiLineString { get; set; } + public MygisMultiPolygon testFieldMultiPolygon { get; set; } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public TableAllTypeEnumType1 testFieldEnum1 { get; set; } + public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } + public TableAllTypeEnumType2 testFieldEnum2 { get; set; } + public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } + } + + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/StringTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/StringTest.cs index 331170d1..2ceacb9d 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/StringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/StringTest.cs @@ -4,693 +4,717 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnectorExpression { - public class StringTest { - - ISelect select => g.mysql.Select(); - - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - class TestEqualsGuid { - public Guid id { get; set; } - public bool IsDeleted { get; set; } - } - - [Fact] - public void Equals__() { - var list = new List(); - list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); - list.Add(g.mysql.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); - list.Add(g.mysql.Select().Where(a => a.IsDeleted.Equals(false)).ToList()); - } - - [Fact] - public void Empty() { - var data = new List(); - data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ifnull(a.`Title`, '') = '') - } - - [Fact] - public void StartsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) - list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) - } - [Fact] - public void EndsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) - } - [Fact] - public void Contains() { - var list = new List(); - list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) - } - [Fact] - public void ToLower() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void ToUpper() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void Substring() { - var data = new List(); - data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) - } - [Fact] - public void Length() { - var data = new List(); - data.Add(select.Where(a => a.Title.Length == 0).ToList()); - data.Add(select.Where(a => a.Title.Length == 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); - data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) - } - [Fact] - public void IndexOf() { - var data = new List(); - data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) - } - [Fact] - public void PadLeft() { - var data = new List(); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void PadRight() { - var data = new List(); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void Trim() { - var data = new List(); - data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void TrimStart() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) - } - [Fact] - public void TrimEnd() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void Replace() { - var data = new List(); - data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) - } - - [Fact] - public void string_IsNullOrEmpty() { - var data = new List(); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); - data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); - } - } +namespace FreeSql.Tests.MySqlConnectorExpression +{ + public class StringTest + { + + ISelect select => g.mysql.Select(); + + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + class TestEqualsGuid + { + public Guid id { get; set; } + public bool IsDeleted { get; set; } + } + + [Fact] + public void Equals__() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); + list.Add(g.mysql.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); + list.Add(g.mysql.Select().Where(a => a.IsDeleted.Equals(false)).ToList()); + } + + [Fact] + public void Empty() + { + var data = new List(); + data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ifnull(a.`Title`, '') = '') + } + + [Fact] + public void StartsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) + list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) + } + [Fact] + public void EndsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) + } + [Fact] + public void Contains() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) + } + [Fact] + public void ToLower() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void ToUpper() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void Substring() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) + } + [Fact] + public void Length() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Length == 0).ToList()); + data.Add(select.Where(a => a.Title.Length == 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); + data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) + } + [Fact] + public void IndexOf() + { + var data = new List(); + data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) + } + [Fact] + public void PadLeft() + { + var data = new List(); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void PadRight() + { + var data = new List(); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void Trim() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void TrimStart() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) + } + [Fact] + public void TrimEnd() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void Replace() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) + } + + [Fact] + public void string_IsNullOrEmpty() + { + var data = new List(); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); + data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/TimeSpanTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/TimeSpanTest.cs index 2f4431c3..0712d905 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/TimeSpanTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlConnectorExpression/TimeSpanTest.cs @@ -4,257 +4,290 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlConnectorExpression { - public class TimeSpanTest { +namespace FreeSql.Tests.MySqlConnectorExpression +{ + public class TimeSpanTest + { - ISelect select => g.mysql.Select(); + ISelect select => g.mysql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } - [Fact] - public void Zero() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) - } - [Fact] - public void Days() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) - } - [Fact] - public void Hours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) - } - [Fact] - public void Milliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) - } - [Fact] - public void Minutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) - } - [Fact] - public void Seconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) - } - [Fact] - public void TotalDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) - } - [Fact] - public void TotalHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) - } - [Fact] - public void TotalMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) - } - [Fact] - public void TotalMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) - } - [Fact] - public void TotalSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') - } + public List Types { get; set; } + } + [Fact] + public void Zero() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) + } + [Fact] + public void Days() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) + } + [Fact] + public void Hours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) + } + [Fact] + public void Milliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) + } + [Fact] + public void Minutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) + } + [Fact] + public void Seconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) + } + [Fact] + public void TotalDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) + } + [Fact] + public void TotalHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) + } + [Fact] + public void TotalMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) + } + [Fact] + public void TotalMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) + } + [Fact] + public void TotalSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') + } - [Fact] - public void TimeSpan_Compare() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void TimeSpan_Equals() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromDays() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromHours() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) - } - [Fact] - public void TimeSpan_FromMilliseconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) - } - [Fact] - public void TimeSpan_FromMinutes() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) - } - [Fact] - public void TimeSpan_FromSeconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) - } - [Fact] - public void TimeSpan_FromTicks() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) - } - [Fact] - public void TimeSpan_Parse() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) - } - } + [Fact] + public void TimeSpan_Compare() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void TimeSpan_Equals() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromDays() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromHours() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) + } + [Fact] + public void TimeSpan_FromMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) + } + [Fact] + public void TimeSpan_FromMinutes() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) + } + [Fact] + public void TimeSpan_FromSeconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) + } + [Fact] + public void TimeSpan_FromTicks() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) + } + [Fact] + public void TimeSpan_Parse() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlDbFirstTest.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlDbFirstTest.cs index 86a3aa7d..5ce6d981 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlDbFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/MySqlConnector/MySqlDbFirstTest.cs @@ -2,20 +2,24 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.MySqlConnector { - public class MySqlDbFirstTest { - [Fact] - public void GetDatabases() { +namespace FreeSql.Tests.MySqlConnector +{ + public class MySqlDbFirstTest + { + [Fact] + public void GetDatabases() + { - var t1 = g.mysql.DbFirst.GetDatabases(); + var t1 = g.mysql.DbFirst.GetDatabases(); - } + } - [Fact] - public void GetTablesByDatabase() { + [Fact] + public void GetTablesByDatabase() + { - var t2 = g.mysql.DbFirst.GetTablesByDatabase(g.mysql.DbFirst.GetDatabases()[0]); + var t2 = g.mysql.DbFirst.GetTablesByDatabase(g.mysql.DbFirst.GetDatabases()[0]); - } - } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/g.cs b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/g.cs index 7f1750d7..ee572d0d 100644 --- a/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/g.cs +++ b/FreeSql.Tests/FreeSql.Tests.Provider.MySqlConnector/g.cs @@ -4,19 +4,22 @@ using System.Diagnostics; using System.Text; -public class g { +public class g +{ - static Lazy mysqlLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd_mysqlconnector;Charset=utf8;SslMode=none;Max pool size=10") - .UseAutoSyncStructure(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .UseLazyLoading(true) - .Build()); - public static IFreeSql mysql => mysqlLazy.Value; + static Lazy mysqlLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd_mysqlconnector;Charset=utf8;SslMode=none;Max pool size=10") + .UseAutoSyncStructure(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .UseLazyLoading(true) + .Build()); + public static IFreeSql mysql => mysqlLazy.Value; } diff --git a/FreeSql.Tests/FreeSql.Tests/DataAnnotations/MySqlFluentTest.cs b/FreeSql.Tests/FreeSql.Tests/DataAnnotations/MySqlFluentTest.cs index 815821ec..2dac212c 100644 --- a/FreeSql.Tests/FreeSql.Tests/DataAnnotations/MySqlFluentTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/DataAnnotations/MySqlFluentTest.cs @@ -4,117 +4,134 @@ using System; using System.Linq; using Xunit; -namespace FreeSql.Tests.DataAnnotations { - public class MySqlFluentTest { +namespace FreeSql.Tests.DataAnnotations +{ + public class MySqlFluentTest + { - public MySqlFluentTest() { - } + public MySqlFluentTest() + { + } - [Fact] - public void DisableSyncStructure() { - Assert.Throws(() => g.mysql.Select().ToList()); + [Fact] + public void DisableSyncStructure() + { + Assert.Throws(() => g.mysql.Select().ToList()); - g.mysql.Select().ToList(); - } - [Table(DisableSyncStructure = true)] - class ModelDisableSyncStructure { - [Column(IsPrimary = false)] - public int pkid { get; set; } - } - class ModelSyncStructure { - [Column(IsPrimary = false)] - public int pkid { get; set; } - } + g.mysql.Select().ToList(); + } + [Table(DisableSyncStructure = true)] + class ModelDisableSyncStructure + { + [Column(IsPrimary = false)] + public int pkid { get; set; } + } + class ModelSyncStructure + { + [Column(IsPrimary = false)] + public int pkid { get; set; } + } - [Fact] - public void AopConfigEntity() { - g.mysql.CodeFirst.ConfigEntity(a => a.Property(b => b.pkid).IsPrimary(true)); + [Fact] + public void AopConfigEntity() + { + g.mysql.CodeFirst.ConfigEntity(a => a.Property(b => b.pkid).IsPrimary(true)); - g.mysql.Aop.ConfigEntity = (s, e) => { - var attr = e.EntityType.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.Schema.TableAttribute; - if (attr != null) { - e.ModifyResult.Name = attr.Name; - } - }; - g.mysql.Aop.ConfigEntityProperty = (s, e) => { - if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any()) { - e.ModifyResult.IsPrimary = true; - } - }; + g.mysql.Aop.ConfigEntity = (s, e) => + { + var attr = e.EntityType.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), false).FirstOrDefault() as System.ComponentModel.DataAnnotations.Schema.TableAttribute; + if (attr != null) + { + e.ModifyResult.Name = attr.Name; + } + }; + g.mysql.Aop.ConfigEntityProperty = (s, e) => + { + if (e.Property.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.KeyAttribute), false).Any()) + { + e.ModifyResult.IsPrimary = true; + } + }; - var tsql1 = g.mysql.Select().WhereDynamic(1).ToSql(); - } - [System.ComponentModel.DataAnnotations.Schema.Table("xxx")] - class ModelAopConfigEntity { - [System.ComponentModel.DataAnnotations.Key] - [Column(IsPrimary = false)] - public int pkid { get; set; } - } + var tsql1 = g.mysql.Select().WhereDynamic(1).ToSql(); + } + [System.ComponentModel.DataAnnotations.Schema.Table("xxx")] + class ModelAopConfigEntity + { + [System.ComponentModel.DataAnnotations.Key] + [Column(IsPrimary = false)] + public int pkid { get; set; } + } - [Fact] - public void Fluent() { - g.mysql.CodeFirst - //.ConfigEntity(a => { - // a.Name("xxdkdkdk1").SelectFilter("a.Id22 > 0"); - // a.Property(b => b.Id).Name("Id22").IsIdentity(true); - // a.Property(b => b.name).DbType("varchar(100)").IsNullable(true); - //}) + [Fact] + public void Fluent() + { + g.mysql.CodeFirst + //.ConfigEntity(a => { + // a.Name("xxdkdkdk1").SelectFilter("a.Id22 > 0"); + // a.Property(b => b.Id).Name("Id22").IsIdentity(true); + // a.Property(b => b.name).DbType("varchar(100)").IsNullable(true); + //}) - .ConfigEntity(typeof(TestFluenttb1), a => { - a.Name("xxdkdkdk1222").SelectFilter("a.Id22dd > 1"); - a.Property("Id").Name("Id22dd").IsIdentity(true); - a.Property("Name").DbType("varchar(101)").IsNullable(true); - }) + .ConfigEntity(typeof(TestFluenttb1), a => + { + a.Name("xxdkdkdk1222").SelectFilter("a.Id22dd > 1"); + a.Property("Id").Name("Id22dd").IsIdentity(true); + a.Property("Name").DbType("varchar(101)").IsNullable(true); + }) - .ConfigEntity(a => { - a.Name("xxdkdkdk2").SelectFilter("a.Idx > 0"); - a.Property(b => b.Id).Name("Id22").IsIdentity(true); - a.Property(b => b.name).DbType("varchar(100)").IsNullable(true); - }) - ; + .ConfigEntity(a => + { + a.Name("xxdkdkdk2").SelectFilter("a.Idx > 0"); + a.Property(b => b.Id).Name("Id22").IsIdentity(true); + a.Property(b => b.name).DbType("varchar(100)").IsNullable(true); + }) + ; - var ddl1 = g.mysql.CodeFirst.GetComparisonDDLStatements(); - var ddl2 = g.mysql.CodeFirst.GetComparisonDDLStatements(); + var ddl1 = g.mysql.CodeFirst.GetComparisonDDLStatements(); + var ddl2 = g.mysql.CodeFirst.GetComparisonDDLStatements(); - var t1id = g.mysql.Insert().AppendData(new TestFluenttb1 { }).ExecuteIdentity(); - var t1 = g.mysql.Select(t1id).ToOne(); + var t1id = g.mysql.Insert().AppendData(new TestFluenttb1 { }).ExecuteIdentity(); + var t1 = g.mysql.Select(t1id).ToOne(); - var t2lastId = g.mysql.Select().Max(a => a.Id); - var t2affrows = g.mysql.Insert().AppendData(new TestFluenttb2 { Id = t2lastId + 1 }).ExecuteAffrows(); - var t2 = g.mysql.Select(t2lastId + 1).ToOne(); - } + var t2lastId = g.mysql.Select().Max(a => a.Id); + var t2affrows = g.mysql.Insert().AppendData(new TestFluenttb2 { Id = t2lastId + 1 }).ExecuteAffrows(); + var t2 = g.mysql.Select(t2lastId + 1).ToOne(); + } - class TestFluenttb1 - { - public int Id { get; set; } + class TestFluenttb1 + { + public int Id { get; set; } - public string name { get; set; } = "defaultValue"; - } + public string name { get; set; } = "defaultValue"; + } - [Table(Name = "cccccdddwww")] - class TestFluenttb2 - { - [Column(Name = "Idx", IsPrimary = true, IsIdentity = false)] - public int Id { get; set; } + [Table(Name = "cccccdddwww")] + class TestFluenttb2 + { + [Column(Name = "Idx", IsPrimary = true, IsIdentity = false)] + public int Id { get; set; } - public string name { get; set; } = "defaultValue"; - } + public string name { get; set; } = "defaultValue"; + } - [Fact] - public void IsIgnore() { - var item = new TestIsIgnore { }; - Assert.Equal(1, g.mysql.Insert().AppendData(item).ExecuteAffrows()); + [Fact] + public void IsIgnore() + { + var item = new TestIsIgnore { }; + Assert.Equal(1, g.mysql.Insert().AppendData(item).ExecuteAffrows()); - var find = g.mysql.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - } + var find = g.mysql.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + } - class TestIsIgnore { - public Guid id { get; set; } + class TestIsIgnore + { + public Guid id { get; set; } - [Column(IsIgnore = true)] - public bool isignore { get; set; } - } - } + [Column(IsIgnore = true)] + public bool isignore { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/DataAnnotations/SqlServerFluentTest.cs b/FreeSql.Tests/FreeSql.Tests/DataAnnotations/SqlServerFluentTest.cs index f4354f51..cd6aee48 100644 --- a/FreeSql.Tests/FreeSql.Tests/DataAnnotations/SqlServerFluentTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/DataAnnotations/SqlServerFluentTest.cs @@ -4,118 +4,130 @@ using System; using System.Data.SqlClient; using Xunit; -namespace FreeSql.Tests.DataAnnotations { - [Collection("SqlServerCollection")] - public class SqlServerFluentTest { +namespace FreeSql.Tests.DataAnnotations +{ + [Collection("SqlServerCollection")] + public class SqlServerFluentTest + { - SqlServerFixture _sqlserverFixture; + SqlServerFixture _sqlserverFixture; - public SqlServerFluentTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public SqlServerFluentTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - [Fact] - public void DisableSyncStructure() { - Assert.Throws(() => _sqlserverFixture.SqlServer.Select().ToList()); + [Fact] + public void DisableSyncStructure() + { + Assert.Throws(() => _sqlserverFixture.SqlServer.Select().ToList()); - _sqlserverFixture.SqlServer.Select().ToList(); - } - [Table(DisableSyncStructure = true)] - class ModelDisableSyncStructure { - [Column(IsPrimary = false)] - public int pkid { get; set; } - } - class ModelSyncStructure { - [Column(IsPrimary = false)] - public int pkid { get; set; } - } + _sqlserverFixture.SqlServer.Select().ToList(); + } + [Table(DisableSyncStructure = true)] + class ModelDisableSyncStructure + { + [Column(IsPrimary = false)] + public int pkid { get; set; } + } + class ModelSyncStructure + { + [Column(IsPrimary = false)] + public int pkid { get; set; } + } - [Fact] - public void Fluent() { - _sqlserverFixture.SqlServer.CodeFirst - //.ConfigEntity(a => { - // a.Name("xxdkdkdk1").SelectFilter("a.Id22 > 0"); - // a.Property(b => b.Id).Name("Id22").IsIdentity(true); - // a.Property(b => b.name).DbType("varchar(100)").IsNullable(true); - //}) + [Fact] + public void Fluent() + { + _sqlserverFixture.SqlServer.CodeFirst + //.ConfigEntity(a => { + // a.Name("xxdkdkdk1").SelectFilter("a.Id22 > 0"); + // a.Property(b => b.Id).Name("Id22").IsIdentity(true); + // a.Property(b => b.name).DbType("varchar(100)").IsNullable(true); + //}) - .ConfigEntity(typeof(TestFluenttb1), a => { - a.Name("xxdkdkdk1222").SelectFilter("a.Id22dd > 1"); - a.Property("Id").Name("Id22dd").IsIdentity(true); - a.Property("Name").DbType("varchar(101)").IsNullable(true); - }) + .ConfigEntity(typeof(TestFluenttb1), a => + { + a.Name("xxdkdkdk1222").SelectFilter("a.Id22dd > 1"); + a.Property("Id").Name("Id22dd").IsIdentity(true); + a.Property("Name").DbType("varchar(101)").IsNullable(true); + }) - .ConfigEntity(a => { - a.Name("xxdkdkdk2").SelectFilter("a.Idx > 0"); - a.Property(b => b.Id).Name("Id22").IsIdentity(true); - a.Property(b => b.name).DbType("varchar(100)").IsNullable(true); - }) - ; + .ConfigEntity(a => + { + a.Name("xxdkdkdk2").SelectFilter("a.Idx > 0"); + a.Property(b => b.Id).Name("Id22").IsIdentity(true); + a.Property(b => b.name).DbType("varchar(100)").IsNullable(true); + }) + ; - var ddl1 = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); - var ddl2 = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); + var ddl1 = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); + var ddl2 = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); - var t1id = _sqlserverFixture.SqlServer.Insert().AppendData(new TestFluenttb1 { }).ExecuteIdentity(); - var t1 = _sqlserverFixture.SqlServer.Select(t1id).ToOne(); + var t1id = _sqlserverFixture.SqlServer.Insert().AppendData(new TestFluenttb1 { }).ExecuteIdentity(); + var t1 = _sqlserverFixture.SqlServer.Select(t1id).ToOne(); - var t2lastId = _sqlserverFixture.SqlServer.Select().Max(a => a.Id); - var t2affrows = _sqlserverFixture.SqlServer.Insert().AppendData(new TestFluenttb2 { Id = t2lastId + 1 }).ExecuteAffrows(); - var t2 = _sqlserverFixture.SqlServer.Select(t2lastId + 1).ToOne(); - } + var t2lastId = _sqlserverFixture.SqlServer.Select().Max(a => a.Id); + var t2affrows = _sqlserverFixture.SqlServer.Insert().AppendData(new TestFluenttb2 { Id = t2lastId + 1 }).ExecuteAffrows(); + var t2 = _sqlserverFixture.SqlServer.Select(t2lastId + 1).ToOne(); + } - [Fact] - public void GroupPrimaryKey() { - _sqlserverFixture.SqlServer.CodeFirst.SyncStructure(); - g.mysql.CodeFirst.SyncStructure(); - g.pgsql.CodeFirst.SyncStructure(); - g.sqlite.CodeFirst.SyncStructure(); - g.oracle.CodeFirst.SyncStructure(); - } + [Fact] + public void GroupPrimaryKey() + { + _sqlserverFixture.SqlServer.CodeFirst.SyncStructure(); + g.mysql.CodeFirst.SyncStructure(); + g.pgsql.CodeFirst.SyncStructure(); + g.sqlite.CodeFirst.SyncStructure(); + g.oracle.CodeFirst.SyncStructure(); + } - class TestFluenttb1 - { - public int Id { get; set; } + class TestFluenttb1 + { + public int Id { get; set; } - public string name { get; set; } = "defaultValue"; - } + public string name { get; set; } = "defaultValue"; + } - [Table(Name = "cccccdddwww")] - class TestFluenttb2 - { - [Column(Name = "Idx", IsPrimary = true, IsIdentity = false)] - public int Id { get; set; } + [Table(Name = "cccccdddwww")] + class TestFluenttb2 + { + [Column(Name = "Idx", IsPrimary = true, IsIdentity = false)] + public int Id { get; set; } - public string name { get; set; } = "defaultValue"; - } + public string name { get; set; } = "defaultValue"; + } - [Table(Name = "test_groupkey")] - class TestgroupkeyTb { - [Column(IsPrimary = true)] - public int Id { get; set; } - [Column(IsPrimary = true)] - public int id2 { get; set; } + [Table(Name = "test_groupkey")] + class TestgroupkeyTb + { + [Column(IsPrimary = true)] + public int Id { get; set; } + [Column(IsPrimary = true)] + public int id2 { get; set; } - public string name { get; set; } = "defaultValue"; - } + public string name { get; set; } = "defaultValue"; + } - [Fact] - public void IsIgnore() { - var item = new TestIsIgnore { }; - Assert.Equal(1, _sqlserverFixture.SqlServer.Insert().AppendData(item).ExecuteAffrows()); + [Fact] + public void IsIgnore() + { + var item = new TestIsIgnore { }; + Assert.Equal(1, _sqlserverFixture.SqlServer.Insert().AppendData(item).ExecuteAffrows()); - var find = _sqlserverFixture.SqlServer.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - } + var find = _sqlserverFixture.SqlServer.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + } - class TestIsIgnore { - public Guid id { get; set; } + class TestIsIgnore + { + public Guid id { get; set; } - [Column(IsIgnore = true)] - public bool isignore { get; set; } - } - } + [Column(IsIgnore = true)] + public bool isignore { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/DataContext/SqlServer/SqlServerCollection.cs b/FreeSql.Tests/FreeSql.Tests/DataContext/SqlServer/SqlServerCollection.cs index 68b6163e..11c2627f 100644 --- a/FreeSql.Tests/FreeSql.Tests/DataContext/SqlServer/SqlServerCollection.cs +++ b/FreeSql.Tests/FreeSql.Tests/DataContext/SqlServer/SqlServerCollection.cs @@ -5,11 +5,11 @@ using Xunit; namespace FreeSql.Tests.DataContext.SqlServer { - [CollectionDefinition("SqlServerCollection")] - public class SqlServerCollection : ICollectionFixture - { - // This class has no code, and is never created. Its purpose is simply - // to be the place to apply [CollectionDefinition] and all the - // ICollectionFixture<> interfaces. - } + [CollectionDefinition("SqlServerCollection")] + public class SqlServerCollection : ICollectionFixture + { + // This class has no code, and is never created. Its purpose is simply + // to be the place to apply [CollectionDefinition] and all the + // ICollectionFixture<> interfaces. + } } diff --git a/FreeSql.Tests/FreeSql.Tests/DataContext/SqlServer/SqlServerFixture.cs b/FreeSql.Tests/FreeSql.Tests/DataContext/SqlServer/SqlServerFixture.cs index bb00942c..712e8b35 100644 --- a/FreeSql.Tests/FreeSql.Tests/DataContext/SqlServer/SqlServerFixture.cs +++ b/FreeSql.Tests/FreeSql.Tests/DataContext/SqlServer/SqlServerFixture.cs @@ -6,56 +6,56 @@ using System.Text; namespace FreeSql.Tests.DataContext.SqlServer { - public class SqlServerFixture : IDisposable - { - public SqlServerFixture() - { - sqlServerLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") - //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=(localdb)\\mssqllocaldb;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseLazyLoading(true) - .UseMonitorCommand(t => Trace.WriteLine(t.CommandText)) - .Build()); + public class SqlServerFixture : IDisposable + { + public SqlServerFixture() + { + sqlServerLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") + //.UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=(localdb)\\mssqllocaldb;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseLazyLoading(true) + .UseMonitorCommand(t => Trace.WriteLine(t.CommandText)) + .Build()); - // ... initialize data in the test database ... - } + // ... initialize data in the test database ... + } - public void Dispose() - { - // ... clean up test data from the database ... - ClearDataBase(); - } + public void Dispose() + { + // ... clean up test data from the database ... + ClearDataBase(); + } - private void ClearDataBase() - { - var dataTables = SqlServer.DbFirst.GetTablesByDatabase(); - if (dataTables.Any(item => item.Name == "TopicAddField" && item.Schema == "dbo2")) - { - SqlServer.Ado.ExecuteNonQuery("TRUNCATE TABLE dbo2.TopicAddField "); - SqlServer.Ado.ExecuteNonQuery("DROP TABLE dbo2.TopicAddField"); - SqlServer.Ado.ExecuteNonQuery("DROP SCHEMA dbo2"); - } + private void ClearDataBase() + { + var dataTables = SqlServer.DbFirst.GetTablesByDatabase(); + if (dataTables.Any(item => item.Name == "TopicAddField" && item.Schema == "dbo2")) + { + SqlServer.Ado.ExecuteNonQuery("TRUNCATE TABLE dbo2.TopicAddField "); + SqlServer.Ado.ExecuteNonQuery("DROP TABLE dbo2.TopicAddField"); + SqlServer.Ado.ExecuteNonQuery("DROP SCHEMA dbo2"); + } - var tempTables = new string[] { "cccccdddwww", "song", "tag", "Song_tag", "tb_alltype", "tb_topic", "tb_topic22", - "tb_topic22211", "tb_topic111333", "TestTypeInfo", "TestTypeInfo333", "TestTypeParentInfo", - "TestTypeParentInfo23123", "xxdkdkdk1222", "xxx"}; - foreach (var tempTable in tempTables) - { - DeleteTmpTable(dataTables, tempTable); - } - } + var tempTables = new string[] { "cccccdddwww", "song", "tag", "Song_tag", "tb_alltype", "tb_topic", "tb_topic22", + "tb_topic22211", "tb_topic111333", "TestTypeInfo", "TestTypeInfo333", "TestTypeParentInfo", + "TestTypeParentInfo23123", "xxdkdkdk1222", "xxx"}; + foreach (var tempTable in tempTables) + { + DeleteTmpTable(dataTables, tempTable); + } + } - private void DeleteTmpTable(List dbTables, string deleteTableName, string schemaName = "dbo") - { - if (dbTables.Any(item => item.Name.ToLower() == deleteTableName.ToLower() && item.Schema.ToLower() == schemaName.ToLower())) - { - SqlServer.Ado.ExecuteNonQuery($"TRUNCATE TABLE {schemaName.ToLower()}.{deleteTableName}"); - SqlServer.Ado.ExecuteNonQuery($"DROP TABLE {schemaName.ToLower()}.{deleteTableName}"); - } - } + private void DeleteTmpTable(List dbTables, string deleteTableName, string schemaName = "dbo") + { + if (dbTables.Any(item => item.Name.ToLower() == deleteTableName.ToLower() && item.Schema.ToLower() == schemaName.ToLower())) + { + SqlServer.Ado.ExecuteNonQuery($"TRUNCATE TABLE {schemaName.ToLower()}.{deleteTableName}"); + SqlServer.Ado.ExecuteNonQuery($"DROP TABLE {schemaName.ToLower()}.{deleteTableName}"); + } + } - private Lazy sqlServerLazy; - public IFreeSql SqlServer => sqlServerLazy.Value; - } + private Lazy sqlServerLazy; + public IFreeSql SqlServer => sqlServerLazy.Value; + } } diff --git a/FreeSql.Tests/FreeSql.Tests/ExpressionTree/GetDataReaderValueBlockExpressionTest.cs b/FreeSql.Tests/FreeSql.Tests/ExpressionTree/GetDataReaderValueBlockExpressionTest.cs index 04939deb..6ae782b5 100644 --- a/FreeSql.Tests/FreeSql.Tests/ExpressionTree/GetDataReaderValueBlockExpressionTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/ExpressionTree/GetDataReaderValueBlockExpressionTest.cs @@ -10,423 +10,440 @@ using Npgsql.LegacyPostgis; using FreeSql.Internal; using System.Linq.Expressions; -namespace FreeSql.ExpressionTree { - public class GetDataReaderValueBlockExpressionTest { +namespace FreeSql.ExpressionTree +{ + public class GetDataReaderValueBlockExpressionTest + { - [Fact] - public void Guid2() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.Empty)); - Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), Guid.Empty)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.NewGuid())); - var newguid = Guid.NewGuid(); - Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid), newguid)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(null)); - Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), null)); + [Fact] + public void Guid2() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.Empty)); + Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), Guid.Empty)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.NewGuid())); + var newguid = Guid.NewGuid(); + Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid), newguid)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(null)); + Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), null)); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(Guid.Empty)); - Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid?), Guid.Empty)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(newguid)); - Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid?), newguid)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(Guid?), null)); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(Guid.Empty)); + Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid?), Guid.Empty)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(newguid)); + Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid?), newguid)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(Guid?), null)); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.Empty.ToString())); - Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), Guid.Empty.ToString())); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(newguid.ToString())); - Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid), newguid.ToString())); - var exp333 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant("-1")); - Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), "-1")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(Guid.Empty.ToString())); + Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), Guid.Empty.ToString())); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant(newguid.ToString())); + Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid), newguid.ToString())); + var exp333 = Utils.GetDataReaderValueBlockExpression(typeof(Guid), Expression.Constant("-1")); + Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid), "-1")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(Guid.Empty.ToString())); - Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid?), Guid.Empty.ToString())); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(newguid.ToString())); - Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid?), newguid.ToString())); - var exp3333 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant("-1")); - Assert.Null(Utils.GetDataReaderValue(typeof(Guid?), "-1")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(Guid.Empty.ToString())); + Assert.Equal(Guid.Empty, Utils.GetDataReaderValue(typeof(Guid?), Guid.Empty.ToString())); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant(newguid.ToString())); + Assert.Equal(newguid, Utils.GetDataReaderValue(typeof(Guid?), newguid.ToString())); + var exp3333 = Utils.GetDataReaderValueBlockExpression(typeof(Guid?), Expression.Constant("-1")); + Assert.Null(Utils.GetDataReaderValue(typeof(Guid?), "-1")); + } - [Fact] - public void Boolean() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(true)); - Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(false)); - Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), false)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(null)); - Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), null)); + [Fact] + public void Boolean() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(true)); + Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(false)); + Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), false)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant(null)); + Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), null)); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(true)); - Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(false)); - Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(bool?), null)); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(true)); + Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(false)); + Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(bool?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(bool?), null)); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("1")); - Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("0")); - Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), false)); - var exp333 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("-1")); - Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true)); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("1")); + Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("0")); + Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool), false)); + var exp333 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("-1")); + Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool), true)); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("true")); - Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("True")); - Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true)); - var exp3333 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("false")); - Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false)); - var exp4444 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("False")); - Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false)); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("true")); + Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("True")); + Assert.Equal(true, Utils.GetDataReaderValue(typeof(bool?), true)); + var exp3333 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("false")); + Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false)); + var exp4444 = Utils.GetDataReaderValueBlockExpression(typeof(bool), Expression.Constant("False")); + Assert.Equal(false, Utils.GetDataReaderValue(typeof(bool?), false)); + } - [Fact] - public void SByte() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(sbyte.MinValue)); - Assert.Equal(sbyte.MinValue, Utils.GetDataReaderValue(typeof(sbyte), sbyte.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(sbyte.MaxValue)); - Assert.Equal(sbyte.MaxValue, Utils.GetDataReaderValue(typeof(sbyte), sbyte.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant("127")); - Assert.Equal((sbyte)127, Utils.GetDataReaderValue(typeof(sbyte), "127")); + [Fact] + public void SByte() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(sbyte.MinValue)); + Assert.Equal(sbyte.MinValue, Utils.GetDataReaderValue(typeof(sbyte), sbyte.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(sbyte.MaxValue)); + Assert.Equal(sbyte.MaxValue, Utils.GetDataReaderValue(typeof(sbyte), sbyte.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant("127")); + Assert.Equal((sbyte)127, Utils.GetDataReaderValue(typeof(sbyte), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(sbyte.MinValue)); - Assert.Equal(sbyte.MinValue, Utils.GetDataReaderValue(typeof(sbyte?), sbyte.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(sbyte.MaxValue)); - Assert.Equal(sbyte.MaxValue, Utils.GetDataReaderValue(typeof(sbyte?), sbyte.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant("127")); - Assert.Equal((sbyte)127, Utils.GetDataReaderValue(typeof(sbyte?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(sbyte.MinValue)); + Assert.Equal(sbyte.MinValue, Utils.GetDataReaderValue(typeof(sbyte?), sbyte.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(sbyte.MaxValue)); + Assert.Equal(sbyte.MaxValue, Utils.GetDataReaderValue(typeof(sbyte?), sbyte.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant("127")); + Assert.Equal((sbyte)127, Utils.GetDataReaderValue(typeof(sbyte?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(null)); - Assert.Equal(default(sbyte), Utils.GetDataReaderValue(typeof(sbyte), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant("aaa")); - Assert.Equal(default(sbyte), Utils.GetDataReaderValue(typeof(sbyte), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant(null)); + Assert.Equal(default(sbyte), Utils.GetDataReaderValue(typeof(sbyte), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte), Expression.Constant("aaa")); + Assert.Equal(default(sbyte), Utils.GetDataReaderValue(typeof(sbyte), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(sbyte?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(sbyte?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(sbyte?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(sbyte?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(sbyte?), "aaa")); + } - [Fact] - public void Short() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(short.MinValue)); - Assert.Equal(short.MinValue, Utils.GetDataReaderValue(typeof(short), short.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(short.MaxValue)); - Assert.Equal(short.MaxValue, Utils.GetDataReaderValue(typeof(short), short.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant("127")); - Assert.Equal((short)127, Utils.GetDataReaderValue(typeof(short), "127")); + [Fact] + public void Short() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(short.MinValue)); + Assert.Equal(short.MinValue, Utils.GetDataReaderValue(typeof(short), short.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(short.MaxValue)); + Assert.Equal(short.MaxValue, Utils.GetDataReaderValue(typeof(short), short.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant("127")); + Assert.Equal((short)127, Utils.GetDataReaderValue(typeof(short), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(short.MinValue)); - Assert.Equal(short.MinValue, Utils.GetDataReaderValue(typeof(short?), short.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(short.MaxValue)); - Assert.Equal(short.MaxValue, Utils.GetDataReaderValue(typeof(short?), short.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant("127")); - Assert.Equal((short)127, Utils.GetDataReaderValue(typeof(short?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(short.MinValue)); + Assert.Equal(short.MinValue, Utils.GetDataReaderValue(typeof(short?), short.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(short.MaxValue)); + Assert.Equal(short.MaxValue, Utils.GetDataReaderValue(typeof(short?), short.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant("127")); + Assert.Equal((short)127, Utils.GetDataReaderValue(typeof(short?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(null)); - Assert.Equal(default(short), Utils.GetDataReaderValue(typeof(short), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant("aaa")); - Assert.Equal(default(short), Utils.GetDataReaderValue(typeof(short), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant(null)); + Assert.Equal(default(short), Utils.GetDataReaderValue(typeof(short), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(short), Expression.Constant("aaa")); + Assert.Equal(default(short), Utils.GetDataReaderValue(typeof(short), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(short?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(short?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(short?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(short?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(short?), "aaa")); + } - [Fact] - public void Int() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(int.MinValue)); - Assert.Equal(int.MinValue, Utils.GetDataReaderValue(typeof(int), int.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(int.MaxValue)); - Assert.Equal(int.MaxValue, Utils.GetDataReaderValue(typeof(int), int.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant("127")); - Assert.Equal((int)127, Utils.GetDataReaderValue(typeof(int), "127")); + [Fact] + public void Int() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(int.MinValue)); + Assert.Equal(int.MinValue, Utils.GetDataReaderValue(typeof(int), int.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(int.MaxValue)); + Assert.Equal(int.MaxValue, Utils.GetDataReaderValue(typeof(int), int.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant("127")); + Assert.Equal((int)127, Utils.GetDataReaderValue(typeof(int), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(int.MinValue)); - Assert.Equal(int.MinValue, Utils.GetDataReaderValue(typeof(int?), int.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(int.MaxValue)); - Assert.Equal(int.MaxValue, Utils.GetDataReaderValue(typeof(int?), int.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant("127")); - Assert.Equal((int)127, Utils.GetDataReaderValue(typeof(int?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(int.MinValue)); + Assert.Equal(int.MinValue, Utils.GetDataReaderValue(typeof(int?), int.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(int.MaxValue)); + Assert.Equal(int.MaxValue, Utils.GetDataReaderValue(typeof(int?), int.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant("127")); + Assert.Equal((int)127, Utils.GetDataReaderValue(typeof(int?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(null)); - Assert.Equal(default(int), Utils.GetDataReaderValue(typeof(int), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant("aaa")); - Assert.Equal(default(int), Utils.GetDataReaderValue(typeof(int), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant(null)); + Assert.Equal(default(int), Utils.GetDataReaderValue(typeof(int), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(int), Expression.Constant("aaa")); + Assert.Equal(default(int), Utils.GetDataReaderValue(typeof(int), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(int?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(int?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(int?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(int?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(int?), "aaa")); + } - [Fact] - public void Long() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(long.MinValue)); - Assert.Equal(long.MinValue, Utils.GetDataReaderValue(typeof(long), long.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(long.MaxValue)); - Assert.Equal(long.MaxValue, Utils.GetDataReaderValue(typeof(long), long.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant("127")); - Assert.Equal((long)127, Utils.GetDataReaderValue(typeof(long), "127")); + [Fact] + public void Long() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(long.MinValue)); + Assert.Equal(long.MinValue, Utils.GetDataReaderValue(typeof(long), long.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(long.MaxValue)); + Assert.Equal(long.MaxValue, Utils.GetDataReaderValue(typeof(long), long.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant("127")); + Assert.Equal((long)127, Utils.GetDataReaderValue(typeof(long), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(long.MinValue)); - Assert.Equal(long.MinValue, Utils.GetDataReaderValue(typeof(long?), long.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(long.MaxValue)); - Assert.Equal(long.MaxValue, Utils.GetDataReaderValue(typeof(long?), long.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant("127")); - Assert.Equal((long)127, Utils.GetDataReaderValue(typeof(long?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(long.MinValue)); + Assert.Equal(long.MinValue, Utils.GetDataReaderValue(typeof(long?), long.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(long.MaxValue)); + Assert.Equal(long.MaxValue, Utils.GetDataReaderValue(typeof(long?), long.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant("127")); + Assert.Equal((long)127, Utils.GetDataReaderValue(typeof(long?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(null)); - Assert.Equal(default(long), Utils.GetDataReaderValue(typeof(long), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant("aaa")); - Assert.Equal(default(long), Utils.GetDataReaderValue(typeof(long), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant(null)); + Assert.Equal(default(long), Utils.GetDataReaderValue(typeof(long), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(long), Expression.Constant("aaa")); + Assert.Equal(default(long), Utils.GetDataReaderValue(typeof(long), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(long?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(long?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(long?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(long?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(long?), "aaa")); + } - [Fact] - public void Byte() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(byte.MinValue)); - Assert.Equal(byte.MinValue, Utils.GetDataReaderValue(typeof(byte), byte.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(byte.MaxValue)); - Assert.Equal(byte.MaxValue, Utils.GetDataReaderValue(typeof(byte), byte.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant("127")); - Assert.Equal((byte)127, Utils.GetDataReaderValue(typeof(byte), "127")); + [Fact] + public void Byte() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(byte.MinValue)); + Assert.Equal(byte.MinValue, Utils.GetDataReaderValue(typeof(byte), byte.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(byte.MaxValue)); + Assert.Equal(byte.MaxValue, Utils.GetDataReaderValue(typeof(byte), byte.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant("127")); + Assert.Equal((byte)127, Utils.GetDataReaderValue(typeof(byte), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(byte.MinValue)); - Assert.Equal(byte.MinValue, Utils.GetDataReaderValue(typeof(byte?), byte.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(byte.MaxValue)); - Assert.Equal(byte.MaxValue, Utils.GetDataReaderValue(typeof(byte?), byte.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant("127")); - Assert.Equal((byte)127, Utils.GetDataReaderValue(typeof(byte?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(byte.MinValue)); + Assert.Equal(byte.MinValue, Utils.GetDataReaderValue(typeof(byte?), byte.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(byte.MaxValue)); + Assert.Equal(byte.MaxValue, Utils.GetDataReaderValue(typeof(byte?), byte.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant("127")); + Assert.Equal((byte)127, Utils.GetDataReaderValue(typeof(byte?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(null)); - Assert.Equal(default(byte), Utils.GetDataReaderValue(typeof(byte), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant("aaa")); - Assert.Equal(default(byte), Utils.GetDataReaderValue(typeof(byte), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant(null)); + Assert.Equal(default(byte), Utils.GetDataReaderValue(typeof(byte), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(byte), Expression.Constant("aaa")); + Assert.Equal(default(byte), Utils.GetDataReaderValue(typeof(byte), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(byte?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(byte?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(byte?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(byte?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(byte?), "aaa")); + } - [Fact] - public void UShort() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(ushort.MinValue)); - Assert.Equal(ushort.MinValue, Utils.GetDataReaderValue(typeof(ushort), ushort.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(ushort.MaxValue)); - Assert.Equal(ushort.MaxValue, Utils.GetDataReaderValue(typeof(ushort), ushort.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant("127")); - Assert.Equal((ushort)127, Utils.GetDataReaderValue(typeof(ushort), "127")); + [Fact] + public void UShort() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(ushort.MinValue)); + Assert.Equal(ushort.MinValue, Utils.GetDataReaderValue(typeof(ushort), ushort.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(ushort.MaxValue)); + Assert.Equal(ushort.MaxValue, Utils.GetDataReaderValue(typeof(ushort), ushort.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant("127")); + Assert.Equal((ushort)127, Utils.GetDataReaderValue(typeof(ushort), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(ushort.MinValue)); - Assert.Equal(ushort.MinValue, Utils.GetDataReaderValue(typeof(ushort?), ushort.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(ushort.MaxValue)); - Assert.Equal(ushort.MaxValue, Utils.GetDataReaderValue(typeof(ushort?), ushort.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant("127")); - Assert.Equal((ushort)127, Utils.GetDataReaderValue(typeof(ushort?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(ushort.MinValue)); + Assert.Equal(ushort.MinValue, Utils.GetDataReaderValue(typeof(ushort?), ushort.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(ushort.MaxValue)); + Assert.Equal(ushort.MaxValue, Utils.GetDataReaderValue(typeof(ushort?), ushort.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant("127")); + Assert.Equal((ushort)127, Utils.GetDataReaderValue(typeof(ushort?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(null)); - Assert.Equal(default(ushort), Utils.GetDataReaderValue(typeof(ushort), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant("aaa")); - Assert.Equal(default(ushort), Utils.GetDataReaderValue(typeof(ushort), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant(null)); + Assert.Equal(default(ushort), Utils.GetDataReaderValue(typeof(ushort), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(ushort), Expression.Constant("aaa")); + Assert.Equal(default(ushort), Utils.GetDataReaderValue(typeof(ushort), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(ushort?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(ushort?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(ushort?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(ushort?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(ushort?), "aaa")); + } - [Fact] - public void UInt() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(uint.MinValue)); - Assert.Equal(uint.MinValue, Utils.GetDataReaderValue(typeof(uint), uint.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(uint.MaxValue)); - Assert.Equal(uint.MaxValue, Utils.GetDataReaderValue(typeof(uint), uint.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant("127")); - Assert.Equal((uint)127, Utils.GetDataReaderValue(typeof(uint), "127")); + [Fact] + public void UInt() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(uint.MinValue)); + Assert.Equal(uint.MinValue, Utils.GetDataReaderValue(typeof(uint), uint.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(uint.MaxValue)); + Assert.Equal(uint.MaxValue, Utils.GetDataReaderValue(typeof(uint), uint.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant("127")); + Assert.Equal((uint)127, Utils.GetDataReaderValue(typeof(uint), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(uint.MinValue)); - Assert.Equal(uint.MinValue, Utils.GetDataReaderValue(typeof(uint?), uint.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(uint.MaxValue)); - Assert.Equal(uint.MaxValue, Utils.GetDataReaderValue(typeof(uint?), uint.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant("127")); - Assert.Equal((uint)127, Utils.GetDataReaderValue(typeof(uint?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(uint.MinValue)); + Assert.Equal(uint.MinValue, Utils.GetDataReaderValue(typeof(uint?), uint.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(uint.MaxValue)); + Assert.Equal(uint.MaxValue, Utils.GetDataReaderValue(typeof(uint?), uint.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant("127")); + Assert.Equal((uint)127, Utils.GetDataReaderValue(typeof(uint?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(null)); - Assert.Equal(default(uint), Utils.GetDataReaderValue(typeof(uint), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant("aaa")); - Assert.Equal(default(uint), Utils.GetDataReaderValue(typeof(uint), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant(null)); + Assert.Equal(default(uint), Utils.GetDataReaderValue(typeof(uint), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(uint), Expression.Constant("aaa")); + Assert.Equal(default(uint), Utils.GetDataReaderValue(typeof(uint), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(uint?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(uint?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(uint?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(uint?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(uint?), "aaa")); + } - [Fact] - public void ULong() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(ulong.MinValue)); - Assert.Equal(ulong.MinValue, Utils.GetDataReaderValue(typeof(ulong), ulong.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(ulong.MaxValue)); - Assert.Equal(ulong.MaxValue, Utils.GetDataReaderValue(typeof(ulong), ulong.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant("127")); - Assert.Equal((ulong)127, Utils.GetDataReaderValue(typeof(ulong), "127")); + [Fact] + public void ULong() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(ulong.MinValue)); + Assert.Equal(ulong.MinValue, Utils.GetDataReaderValue(typeof(ulong), ulong.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(ulong.MaxValue)); + Assert.Equal(ulong.MaxValue, Utils.GetDataReaderValue(typeof(ulong), ulong.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant("127")); + Assert.Equal((ulong)127, Utils.GetDataReaderValue(typeof(ulong), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(ulong.MinValue)); - Assert.Equal(ulong.MinValue, Utils.GetDataReaderValue(typeof(ulong?), ulong.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(ulong.MaxValue)); - Assert.Equal(ulong.MaxValue, Utils.GetDataReaderValue(typeof(ulong?), ulong.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant("127")); - Assert.Equal((ulong)127, Utils.GetDataReaderValue(typeof(ulong?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(ulong.MinValue)); + Assert.Equal(ulong.MinValue, Utils.GetDataReaderValue(typeof(ulong?), ulong.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(ulong.MaxValue)); + Assert.Equal(ulong.MaxValue, Utils.GetDataReaderValue(typeof(ulong?), ulong.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant("127")); + Assert.Equal((ulong)127, Utils.GetDataReaderValue(typeof(ulong?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(null)); - Assert.Equal(default(ulong), Utils.GetDataReaderValue(typeof(ulong), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant("aaa")); - Assert.Equal(default(ulong), Utils.GetDataReaderValue(typeof(ulong), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant(null)); + Assert.Equal(default(ulong), Utils.GetDataReaderValue(typeof(ulong), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(ulong), Expression.Constant("aaa")); + Assert.Equal(default(ulong), Utils.GetDataReaderValue(typeof(ulong), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(ulong?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(ulong?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(ulong?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(ulong?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(ulong?), "aaa")); + } - [Fact] - public void Float() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(float.MinValue)); - Assert.Equal(float.MinValue, Utils.GetDataReaderValue(typeof(float), float.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(float.MaxValue)); - Assert.Equal(float.MaxValue, Utils.GetDataReaderValue(typeof(float), float.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant("127")); - Assert.Equal((float)127, Utils.GetDataReaderValue(typeof(float), "127")); + [Fact] + public void Float() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(float.MinValue)); + Assert.Equal(float.MinValue, Utils.GetDataReaderValue(typeof(float), float.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(float.MaxValue)); + Assert.Equal(float.MaxValue, Utils.GetDataReaderValue(typeof(float), float.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant("127")); + Assert.Equal((float)127, Utils.GetDataReaderValue(typeof(float), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(float.MinValue)); - Assert.Equal(float.MinValue, Utils.GetDataReaderValue(typeof(float?), float.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(float.MaxValue)); - Assert.Equal(float.MaxValue, Utils.GetDataReaderValue(typeof(float?), float.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant("127")); - Assert.Equal((float)127, Utils.GetDataReaderValue(typeof(float?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(float.MinValue)); + Assert.Equal(float.MinValue, Utils.GetDataReaderValue(typeof(float?), float.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(float.MaxValue)); + Assert.Equal(float.MaxValue, Utils.GetDataReaderValue(typeof(float?), float.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant("127")); + Assert.Equal((float)127, Utils.GetDataReaderValue(typeof(float?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(null)); - Assert.Equal(default(float), Utils.GetDataReaderValue(typeof(float), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant("aaa")); - Assert.Equal(default(float), Utils.GetDataReaderValue(typeof(float), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant(null)); + Assert.Equal(default(float), Utils.GetDataReaderValue(typeof(float), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(float), Expression.Constant("aaa")); + Assert.Equal(default(float), Utils.GetDataReaderValue(typeof(float), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(float?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(float?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(float?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(float?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(float?), "aaa")); + } - [Fact] - public void Double() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(double.MinValue)); - Assert.Equal(double.MinValue, Utils.GetDataReaderValue(typeof(double), double.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(double.MaxValue)); - Assert.Equal(double.MaxValue, Utils.GetDataReaderValue(typeof(double), double.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant("127")); - Assert.Equal((double)127, Utils.GetDataReaderValue(typeof(double), "127")); + [Fact] + public void Double() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(double.MinValue)); + Assert.Equal(double.MinValue, Utils.GetDataReaderValue(typeof(double), double.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(double.MaxValue)); + Assert.Equal(double.MaxValue, Utils.GetDataReaderValue(typeof(double), double.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant("127")); + Assert.Equal((double)127, Utils.GetDataReaderValue(typeof(double), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(double.MinValue)); - Assert.Equal(double.MinValue, Utils.GetDataReaderValue(typeof(double?), double.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(double.MaxValue)); - Assert.Equal(double.MaxValue, Utils.GetDataReaderValue(typeof(double?), double.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant("127")); - Assert.Equal((double)127, Utils.GetDataReaderValue(typeof(double?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(double.MinValue)); + Assert.Equal(double.MinValue, Utils.GetDataReaderValue(typeof(double?), double.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(double.MaxValue)); + Assert.Equal(double.MaxValue, Utils.GetDataReaderValue(typeof(double?), double.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant("127")); + Assert.Equal((double)127, Utils.GetDataReaderValue(typeof(double?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(null)); - Assert.Equal(default(double), Utils.GetDataReaderValue(typeof(double), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant("aaa")); - Assert.Equal(default(double), Utils.GetDataReaderValue(typeof(double), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant(null)); + Assert.Equal(default(double), Utils.GetDataReaderValue(typeof(double), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(double), Expression.Constant("aaa")); + Assert.Equal(default(double), Utils.GetDataReaderValue(typeof(double), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(double?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(double?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(double?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(double?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(double?), "aaa")); + } - [Fact] - public void Decimal() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(decimal.MinValue)); - Assert.Equal(decimal.MinValue, Utils.GetDataReaderValue(typeof(decimal), decimal.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(decimal.MaxValue)); - Assert.Equal(decimal.MaxValue, Utils.GetDataReaderValue(typeof(decimal), decimal.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant("127")); - Assert.Equal((decimal)127, Utils.GetDataReaderValue(typeof(decimal), "127")); + [Fact] + public void Decimal() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(decimal.MinValue)); + Assert.Equal(decimal.MinValue, Utils.GetDataReaderValue(typeof(decimal), decimal.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(decimal.MaxValue)); + Assert.Equal(decimal.MaxValue, Utils.GetDataReaderValue(typeof(decimal), decimal.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant("127")); + Assert.Equal((decimal)127, Utils.GetDataReaderValue(typeof(decimal), "127")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(decimal.MinValue)); - Assert.Equal(decimal.MinValue, Utils.GetDataReaderValue(typeof(decimal?), decimal.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(decimal.MaxValue)); - Assert.Equal(decimal.MaxValue, Utils.GetDataReaderValue(typeof(decimal?), decimal.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant("127")); - Assert.Equal((decimal)127, Utils.GetDataReaderValue(typeof(decimal?), "127")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(decimal.MinValue)); + Assert.Equal(decimal.MinValue, Utils.GetDataReaderValue(typeof(decimal?), decimal.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(decimal.MaxValue)); + Assert.Equal(decimal.MaxValue, Utils.GetDataReaderValue(typeof(decimal?), decimal.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant("127")); + Assert.Equal((decimal)127, Utils.GetDataReaderValue(typeof(decimal?), "127")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(null)); - Assert.Equal(default(decimal), Utils.GetDataReaderValue(typeof(decimal), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant("aaa")); - Assert.Equal(default(decimal), Utils.GetDataReaderValue(typeof(decimal), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant(null)); + Assert.Equal(default(decimal), Utils.GetDataReaderValue(typeof(decimal), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(decimal), Expression.Constant("aaa")); + Assert.Equal(default(decimal), Utils.GetDataReaderValue(typeof(decimal), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(decimal?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(decimal?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(decimal?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(decimal?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(decimal?), "aaa")); + } - [Fact] - public void DateTime2() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(DateTime.MinValue)); - Assert.Equal(DateTime.MinValue, Utils.GetDataReaderValue(typeof(DateTime), DateTime.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(DateTime.MaxValue)); - Assert.Equal(DateTime.MaxValue, Utils.GetDataReaderValue(typeof(DateTime), DateTime.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant("2000-1-1")); - Assert.Equal(DateTime.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTime), "2000-1-1")); + [Fact] + public void DateTime2() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(DateTime.MinValue)); + Assert.Equal(DateTime.MinValue, Utils.GetDataReaderValue(typeof(DateTime), DateTime.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(DateTime.MaxValue)); + Assert.Equal(DateTime.MaxValue, Utils.GetDataReaderValue(typeof(DateTime), DateTime.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant("2000-1-1")); + Assert.Equal(DateTime.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTime), "2000-1-1")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(DateTime.MinValue)); - Assert.Equal(DateTime.MinValue, Utils.GetDataReaderValue(typeof(DateTime?), DateTime.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(DateTime.MaxValue)); - Assert.Equal(DateTime.MaxValue, Utils.GetDataReaderValue(typeof(DateTime?), DateTime.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant("2000-1-1")); - Assert.Equal(DateTime.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTime?), "2000-1-1")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(DateTime.MinValue)); + Assert.Equal(DateTime.MinValue, Utils.GetDataReaderValue(typeof(DateTime?), DateTime.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(DateTime.MaxValue)); + Assert.Equal(DateTime.MaxValue, Utils.GetDataReaderValue(typeof(DateTime?), DateTime.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant("2000-1-1")); + Assert.Equal(DateTime.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTime?), "2000-1-1")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(null)); - Assert.Equal(default(DateTime), Utils.GetDataReaderValue(typeof(DateTime), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant("aaa")); - Assert.Equal(default(DateTime), Utils.GetDataReaderValue(typeof(DateTime), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant(null)); + Assert.Equal(default(DateTime), Utils.GetDataReaderValue(typeof(DateTime), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime), Expression.Constant("aaa")); + Assert.Equal(default(DateTime), Utils.GetDataReaderValue(typeof(DateTime), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(DateTime?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(DateTime?), "aaa")); - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(DateTime?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTime?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(DateTime?), "aaa")); + } - [Fact] - public void DateTimeOffset2() { - var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(DateTimeOffset.MinValue)); - Assert.Equal(DateTimeOffset.MinValue, Utils.GetDataReaderValue(typeof(DateTimeOffset), DateTimeOffset.MinValue)); - var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(DateTimeOffset.MaxValue)); - Assert.Equal(DateTimeOffset.MaxValue, Utils.GetDataReaderValue(typeof(DateTimeOffset), DateTimeOffset.MaxValue)); - var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant("2000-1-1")); - Assert.Equal(DateTimeOffset.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTimeOffset), "2000-1-1")); + [Fact] + public void DateTimeOffset2() + { + var exp1 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(DateTimeOffset.MinValue)); + Assert.Equal(DateTimeOffset.MinValue, Utils.GetDataReaderValue(typeof(DateTimeOffset), DateTimeOffset.MinValue)); + var exp2 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(DateTimeOffset.MaxValue)); + Assert.Equal(DateTimeOffset.MaxValue, Utils.GetDataReaderValue(typeof(DateTimeOffset), DateTimeOffset.MaxValue)); + var exp3 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant("2000-1-1")); + Assert.Equal(DateTimeOffset.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTimeOffset), "2000-1-1")); - var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(DateTimeOffset.MinValue)); - Assert.Equal(DateTimeOffset.MinValue, Utils.GetDataReaderValue(typeof(DateTimeOffset?), DateTimeOffset.MinValue)); - var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(DateTimeOffset.MaxValue)); - Assert.Equal(DateTimeOffset.MaxValue, Utils.GetDataReaderValue(typeof(DateTimeOffset?), DateTimeOffset.MaxValue)); - var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant("2000-1-1")); - Assert.Equal(DateTimeOffset.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTimeOffset?), "2000-1-1")); + var exp11 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(DateTimeOffset.MinValue)); + Assert.Equal(DateTimeOffset.MinValue, Utils.GetDataReaderValue(typeof(DateTimeOffset?), DateTimeOffset.MinValue)); + var exp22 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(DateTimeOffset.MaxValue)); + Assert.Equal(DateTimeOffset.MaxValue, Utils.GetDataReaderValue(typeof(DateTimeOffset?), DateTimeOffset.MaxValue)); + var exp33 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant("2000-1-1")); + Assert.Equal(DateTimeOffset.Parse("2000-1-1"), Utils.GetDataReaderValue(typeof(DateTimeOffset?), "2000-1-1")); - var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(null)); - Assert.Equal(default(DateTimeOffset), Utils.GetDataReaderValue(typeof(DateTimeOffset), null)); - var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant("aaa")); - Assert.Equal(default(DateTimeOffset), Utils.GetDataReaderValue(typeof(DateTimeOffset), "aaa")); + var exp111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant(null)); + Assert.Equal(default(DateTimeOffset), Utils.GetDataReaderValue(typeof(DateTimeOffset), null)); + var exp222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset), Expression.Constant("aaa")); + Assert.Equal(default(DateTimeOffset), Utils.GetDataReaderValue(typeof(DateTimeOffset), "aaa")); - var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(null)); - Assert.Null(Utils.GetDataReaderValue(typeof(DateTimeOffset?), null)); - var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant("aaa")); - Assert.Null(Utils.GetDataReaderValue(typeof(DateTimeOffset?), "aaa")); - } - } + var exp1111 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant(null)); + Assert.Null(Utils.GetDataReaderValue(typeof(DateTimeOffset?), null)); + var exp2222 = Utils.GetDataReaderValueBlockExpression(typeof(DateTimeOffset?), Expression.Constant("aaa")); + Assert.Null(Utils.GetDataReaderValue(typeof(DateTimeOffset?), "aaa")); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Extensions/LambadaExpressionExtensionsTest.cs b/FreeSql.Tests/FreeSql.Tests/Extensions/LambadaExpressionExtensionsTest.cs index ca387c1e..4c6d8e38 100644 --- a/FreeSql.Tests/FreeSql.Tests/Extensions/LambadaExpressionExtensionsTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Extensions/LambadaExpressionExtensionsTest.cs @@ -3,41 +3,47 @@ using System.Collections.Generic; using System.Linq.Expressions; using Xunit; -namespace FreeSql.Tests.Extensions { - public class LambadaExpressionExtensionsTest { +namespace FreeSql.Tests.Extensions +{ + public class LambadaExpressionExtensionsTest + { - [Fact] - public void And() { - Expression> where = a => a.id == Guid.Empty; + [Fact] + public void And() + { + Expression> where = a => a.id == Guid.Empty; - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000' AND a.\"num\" > 0)", g.sqlite.Select().Where(where.And(b => b.num > 0)).ToSql().Replace("\r\n", "")); - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.And(false, b => b.num > 0)).ToSql().Replace("\r\n", "")); - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000' AND a.\"num\" = 1 AND a.\"num\" = 2)", g.sqlite.Select().Where(where.And(b => b.num == 1).And(b => b.num == 2)).ToSql().Replace("\r\n", "")); - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.And(false, b => b.num == 1).And(false, c => c.num == 2)).ToSql().Replace("\r\n", "")); - } + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000' AND a.\"num\" > 0)", g.sqlite.Select().Where(where.And(b => b.num > 0)).ToSql().Replace("\r\n", "")); + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.And(false, b => b.num > 0)).ToSql().Replace("\r\n", "")); + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000' AND a.\"num\" = 1 AND a.\"num\" = 2)", g.sqlite.Select().Where(where.And(b => b.num == 1).And(b => b.num == 2)).ToSql().Replace("\r\n", "")); + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.And(false, b => b.num == 1).And(false, c => c.num == 2)).ToSql().Replace("\r\n", "")); + } - [Fact] - public void Or() { - Expression> where = a => a.id == Guid.Empty; + [Fact] + public void Or() + { + Expression> where = a => a.id == Guid.Empty; - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE ((a.\"id\" = '00000000-0000-0000-0000-000000000000' OR a.\"num\" > 0))", g.sqlite.Select().Where(where.Or(b => b.num > 0)).ToSql().Replace("\r\n", "")); - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.Or(false, b => b.num > 0)).ToSql().Replace("\r\n", "")); - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (((a.\"id\" = '00000000-0000-0000-0000-000000000000' OR a.\"num\" = 1) OR a.\"num\" = 2))", g.sqlite.Select().Where(where.Or(b => b.num == 1).Or(b => b.num == 2)).ToSql().Replace("\r\n", "")); - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.Or(false, b => b.num == 1).Or(false, c => c.num == 2)).ToSql().Replace("\r\n", "")); - } + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE ((a.\"id\" = '00000000-0000-0000-0000-000000000000' OR a.\"num\" > 0))", g.sqlite.Select().Where(where.Or(b => b.num > 0)).ToSql().Replace("\r\n", "")); + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.Or(false, b => b.num > 0)).ToSql().Replace("\r\n", "")); + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (((a.\"id\" = '00000000-0000-0000-0000-000000000000' OR a.\"num\" = 1) OR a.\"num\" = 2))", g.sqlite.Select().Where(where.Or(b => b.num == 1).Or(b => b.num == 2)).ToSql().Replace("\r\n", "")); + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.Or(false, b => b.num == 1).Or(false, c => c.num == 2)).ToSql().Replace("\r\n", "")); + } - [Fact] - public void Not() { - Expression> where = a => a.id == Guid.Empty; + [Fact] + public void Not() + { + Expression> where = a => a.id == Guid.Empty; - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (not(a.\"id\" = '00000000-0000-0000-0000-000000000000'))", g.sqlite.Select().Where(where.Not()).ToSql().Replace("\r\n", "")); - Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.Not(false)).ToSql().Replace("\r\n", "")); - } + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (not(a.\"id\" = '00000000-0000-0000-0000-000000000000'))", g.sqlite.Select().Where(where.Not()).ToSql().Replace("\r\n", "")); + Assert.Equal("SELECT a.\"id\", a.\"num\" FROM \"testExpAddOr\" a WHERE (a.\"id\" = '00000000-0000-0000-0000-000000000000')", g.sqlite.Select().Where(where.Not(false)).ToSql().Replace("\r\n", "")); + } - class testExpAddOr { - public Guid id { get; set; } + class testExpAddOr + { + public Guid id { get; set; } - public int num { get; set; } - } - } + public int num { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Extensions/StringExtensionsTest.cs b/FreeSql.Tests/FreeSql.Tests/Extensions/StringExtensionsTest.cs index c7352c24..5b885fca 100644 --- a/FreeSql.Tests/FreeSql.Tests/Extensions/StringExtensionsTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Extensions/StringExtensionsTest.cs @@ -1,65 +1,70 @@ using Xunit; -namespace FreeSql.Tests.Extensions { - public class StringExtensionsTest { - [Fact] - public void FormatMySql() { +namespace FreeSql.Tests.Extensions +{ + public class StringExtensionsTest + { + [Fact] + public void FormatMySql() + { - Assert.Empty(((string)null).FormatMySql("11")); - Assert.Equal("a=1", "a={0}".FormatMySql(1)); - Assert.Equal("a =1", "a ={0}".FormatMySql(1)); - Assert.Equal("a = 1", "a = {0}".FormatMySql(1)); - Assert.Equal("a='a'", "a={0}".FormatMySql('a')); - Assert.Equal("a ='a'", "a ={0}".FormatMySql('a')); - Assert.Equal("a = 'a'", "a = {0}".FormatMySql('a')); + Assert.Empty(((string)null).FormatMySql("11")); + Assert.Equal("a=1", "a={0}".FormatMySql(1)); + Assert.Equal("a =1", "a ={0}".FormatMySql(1)); + Assert.Equal("a = 1", "a = {0}".FormatMySql(1)); + Assert.Equal("a='a'", "a={0}".FormatMySql('a')); + Assert.Equal("a ='a'", "a ={0}".FormatMySql('a')); + Assert.Equal("a = 'a'", "a = {0}".FormatMySql('a')); - Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatMySql(1, null)); - Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatMySql(1, null)); - Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatMySql(1, null)); + Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatMySql(1, null)); + Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatMySql(1, null)); + Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatMySql(1, null)); - Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatMySql(1, null, new[] { 1, 2, 3, 4 })); - Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatMySql(1, null, null)); - Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatMySql(1, null, null)); - } + Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatMySql(1, null, new[] { 1, 2, 3, 4 })); + Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatMySql(1, null, null)); + Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatMySql(1, null, null)); + } - [Fact] - public void FormatSqlServer() { + [Fact] + public void FormatSqlServer() + { - Assert.Empty(((string)null).FormatSqlServer("11")); - Assert.Equal("a=1", "a={0}".FormatSqlServer(1)); - Assert.Equal("a =1", "a ={0}".FormatSqlServer(1)); - Assert.Equal("a = 1", "a = {0}".FormatSqlServer(1)); - Assert.Equal("a='a'", "a={0}".FormatSqlServer('a')); - Assert.Equal("a ='a'", "a ={0}".FormatSqlServer('a')); - Assert.Equal("a = 'a'", "a = {0}".FormatSqlServer('a')); + Assert.Empty(((string)null).FormatSqlServer("11")); + Assert.Equal("a=1", "a={0}".FormatSqlServer(1)); + Assert.Equal("a =1", "a ={0}".FormatSqlServer(1)); + Assert.Equal("a = 1", "a = {0}".FormatSqlServer(1)); + Assert.Equal("a='a'", "a={0}".FormatSqlServer('a')); + Assert.Equal("a ='a'", "a ={0}".FormatSqlServer('a')); + Assert.Equal("a = 'a'", "a = {0}".FormatSqlServer('a')); - Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatSqlServer(1, null)); - Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatSqlServer(1, null)); - Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatSqlServer(1, null)); + Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatSqlServer(1, null)); + Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatSqlServer(1, null)); + Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatSqlServer(1, null)); - Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, new[] { 1, 2, 3, 4 })); - Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, null)); - Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null)); - } + Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, new[] { 1, 2, 3, 4 })); + Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, null)); + Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null)); + } - [Fact] - public void FormatPostgreSQL() { + [Fact] + public void FormatPostgreSQL() + { - Assert.Empty(((string)null).FormatPostgreSQL("11")); - Assert.Equal("a=1", "a={0}".FormatPostgreSQL(1)); - Assert.Equal("a =1", "a ={0}".FormatPostgreSQL(1)); - Assert.Equal("a = 1", "a = {0}".FormatPostgreSQL(1)); - Assert.Equal("a='a'", "a={0}".FormatPostgreSQL('a')); - Assert.Equal("a ='a'", "a ={0}".FormatPostgreSQL('a')); - Assert.Equal("a = 'a'", "a = {0}".FormatPostgreSQL('a')); + Assert.Empty(((string)null).FormatPostgreSQL("11")); + Assert.Equal("a=1", "a={0}".FormatPostgreSQL(1)); + Assert.Equal("a =1", "a ={0}".FormatPostgreSQL(1)); + Assert.Equal("a = 1", "a = {0}".FormatPostgreSQL(1)); + Assert.Equal("a='a'", "a={0}".FormatPostgreSQL('a')); + Assert.Equal("a ='a'", "a ={0}".FormatPostgreSQL('a')); + Assert.Equal("a = 'a'", "a = {0}".FormatPostgreSQL('a')); - Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatPostgreSQL(1, null)); - Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatPostgreSQL(1, null)); - Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatPostgreSQL(1, null)); + Assert.Equal("a=1 and b IS NULL", "a={0} and b={1}".FormatPostgreSQL(1, null)); + Assert.Equal("a =1 and b IS NULL", "a ={0} and b ={1}".FormatPostgreSQL(1, null)); + Assert.Equal("a = 1 and b IS NULL", "a = {0} and b = {1}".FormatPostgreSQL(1, null)); - Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatPostgreSQL(1, null, new[] { 1, 2, 3, 4 })); - Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, null)); - Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null)); - } - } + Assert.Equal("a=1 and b IS NULL and c in (1,2,3,4)", "a={0} and b={1} and c in {2}".FormatPostgreSQL(1, null, new[] { 1, 2, 3, 4 })); + Assert.Equal("a=1 and b IS NULL and c IS NULL", "a={0} and b={1} and c in {2}".FormatSqlServer(1, null, null)); + Assert.Equal("a=1 and b IS NULL and c not IS NULL", "a={0} and b={1} and c not in {2}".FormatSqlServer(1, null, null)); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/LinqToSql/SqliteLinqToSqlTests.cs b/FreeSql.Tests/FreeSql.Tests/LinqToSql/SqliteLinqToSqlTests.cs index 40efaa79..555d7c83 100644 --- a/FreeSql.Tests/FreeSql.Tests/LinqToSql/SqliteLinqToSqlTests.cs +++ b/FreeSql.Tests/FreeSql.Tests/LinqToSql/SqliteLinqToSqlTests.cs @@ -3,185 +3,200 @@ using System; using System.Linq; using Xunit; -namespace FreeSql.Tests.LinqToSql { +namespace FreeSql.Tests.LinqToSql +{ - class TestLinqToSql { - public Guid id { get; set; } + class TestLinqToSql + { + public Guid id { get; set; } - public string name { get; set; } + public string name { get; set; } - public int click { get; set; } = 10; + public int click { get; set; } = 10; - public DateTime createtime { get; set; } = DateTime.Now; - } - class TestLinqToSqlComment { - public Guid id { get; set; } + public DateTime createtime { get; set; } = DateTime.Now; + } + class TestLinqToSqlComment + { + public Guid id { get; set; } - public Guid TestLinqToSqlId { get; set; } - public TestLinqToSql TEstLinqToSql { get; set; } + public Guid TestLinqToSqlId { get; set; } + public TestLinqToSql TEstLinqToSql { get; set; } - public string text { get; set; } - - public DateTime createtime { get; set; } = DateTime.Now; - } + public string text { get; set; } - public class SqliteLinqToSqlTests { + public DateTime createtime { get; set; } = DateTime.Now; + } - [Fact] - public void Where() { - var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(item).ExecuteAffrows(); + public class SqliteLinqToSqlTests + { - var t1 = (from a in g.sqlite.Select() - where a.id == item.id - select a).ToList(); - Assert.True(t1.Any()); - Assert.Equal(item.id, t1[0].id); - } + [Fact] + public void Where() + { + var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(item).ExecuteAffrows(); - [Fact] - public void Select() { - var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(item).ExecuteAffrows(); + var t1 = (from a in g.sqlite.Select() + where a.id == item.id + select a).ToList(); + Assert.True(t1.Any()); + Assert.Equal(item.id, t1[0].id); + } - var t1 = (from a in g.sqlite.Select() - where a.id == item.id - select new { a.id }).ToList(); - Assert.True(t1.Any()); - Assert.Equal(item.id, t1[0].id); - } + [Fact] + public void Select() + { + var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(item).ExecuteAffrows(); - [Fact] - public void GroupBy() { - var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(item).ExecuteAffrows(); + var t1 = (from a in g.sqlite.Select() + where a.id == item.id + select new { a.id }).ToList(); + Assert.True(t1.Any()); + Assert.Equal(item.id, t1[0].id); + } - var t1 = (from a in g.sqlite.Select() - where a.id == item.id - group a by new {a.id, a.name } into g - select new { - g.Key.id, g.Key.name, - cou = g.Count(), - avg = g.Avg(g.Value.click), - sum = g.Sum(g.Value.click), - max = g.Max(g.Value.click), - min = g.Min(g.Value.click) - }).ToList(); - Assert.True(t1.Any()); - Assert.Equal(item.id, t1.First().id); - } + [Fact] + public void GroupBy() + { + var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(item).ExecuteAffrows(); - [Fact] - public void CaseWhen() { - var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(item).ExecuteAffrows(); + var t1 = (from a in g.sqlite.Select() + where a.id == item.id + group a by new { a.id, a.name } into g + select new + { + g.Key.id, + g.Key.name, + cou = g.Count(), + avg = g.Avg(g.Value.click), + sum = g.Sum(g.Value.click), + max = g.Max(g.Value.click), + min = g.Min(g.Value.click) + }).ToList(); + Assert.True(t1.Any()); + Assert.Equal(item.id, t1.First().id); + } - var t1 = (from a in g.sqlite.Select() - where a.id == item.id - select new { - a.id, - a.name, - testsub = new { - time = a.click > 10 ? "" : "Сڻ" - } - }).ToList(); - Assert.True(t1.Any()); - Assert.Equal(item.id, t1[0].id); - Assert.Equal("Сڻ", t1[0].testsub.time); - } + [Fact] + public void CaseWhen() + { + var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(item).ExecuteAffrows(); - [Fact] - public void Join() { - var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(item).ExecuteAffrows(); - var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(comment).ExecuteAffrows(); + var t1 = (from a in g.sqlite.Select() + where a.id == item.id + select new + { + a.id, + a.name, + testsub = new + { + time = a.click > 10 ? "" : "Сڻ" + } + }).ToList(); + Assert.True(t1.Any()); + Assert.Equal(item.id, t1[0].id); + Assert.Equal("Сڻ", t1[0].testsub.time); + } - var t1 = (from a in g.sqlite.Select() - join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId - select a).ToList(); - Assert.True(t1.Any()); - //Assert.Equal(item.id, t1[0].id); + [Fact] + public void Join() + { + var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(item).ExecuteAffrows(); + var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(comment).ExecuteAffrows(); - var t2 = (from a in g.sqlite.Select() - join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId - select new { a.id, bid = b.id }).ToList(); - Assert.True(t2.Any()); - //Assert.Equal(item.id, t2[0].id); - //Assert.Equal(comment.id, t2[0].bid); + var t1 = (from a in g.sqlite.Select() + join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId + select a).ToList(); + Assert.True(t1.Any()); + //Assert.Equal(item.id, t1[0].id); - var t3 = (from a in g.sqlite.Select() - join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId - where a.id == item.id - select new { a.id, bid = b.id }).ToList(); - Assert.True(t3.Any()); - Assert.Equal(item.id, t3[0].id); - Assert.Equal(comment.id, t3[0].bid); - } + var t2 = (from a in g.sqlite.Select() + join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId + select new { a.id, bid = b.id }).ToList(); + Assert.True(t2.Any()); + //Assert.Equal(item.id, t2[0].id); + //Assert.Equal(comment.id, t2[0].bid); - [Fact] - public void LeftJoin() { - var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(item).ExecuteAffrows(); - var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(comment).ExecuteAffrows(); + var t3 = (from a in g.sqlite.Select() + join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId + where a.id == item.id + select new { a.id, bid = b.id }).ToList(); + Assert.True(t3.Any()); + Assert.Equal(item.id, t3[0].id); + Assert.Equal(comment.id, t3[0].bid); + } - var t1 = (from a in g.sqlite.Select() - join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId into temp - from tc in temp.DefaultIfEmpty() - select a).ToList(); - Assert.True(t1.Any()); - //Assert.Equal(item.id, t1[0].id); + [Fact] + public void LeftJoin() + { + var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(item).ExecuteAffrows(); + var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(comment).ExecuteAffrows(); - var t2 = (from a in g.sqlite.Select() - join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId into temp - from tc in temp.DefaultIfEmpty() - select new { a.id, bid = tc.id }).ToList(); - Assert.True(t2.Any()); - //Assert.Equal(item.id, t2[0].id); - //Assert.Equal(comment.id, t2[0].bid); + var t1 = (from a in g.sqlite.Select() + join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId into temp + from tc in temp.DefaultIfEmpty() + select a).ToList(); + Assert.True(t1.Any()); + //Assert.Equal(item.id, t1[0].id); - var t3 = (from a in g.sqlite.Select() - join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId into temp - from tc in temp.DefaultIfEmpty() - where a.id == item.id - select new { a.id, bid = tc.id }).ToList(); - Assert.True(t3.Any()); - Assert.Equal(item.id, t3[0].id); - Assert.Equal(comment.id, t3[0].bid); - } + var t2 = (from a in g.sqlite.Select() + join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId into temp + from tc in temp.DefaultIfEmpty() + select new { a.id, bid = tc.id }).ToList(); + Assert.True(t2.Any()); + //Assert.Equal(item.id, t2[0].id); + //Assert.Equal(comment.id, t2[0].bid); - [Fact] - public void From() { - var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(item).ExecuteAffrows(); - var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; - g.sqlite.Insert().AppendData(comment).ExecuteAffrows(); + var t3 = (from a in g.sqlite.Select() + join b in g.sqlite.Select() on a.id equals b.TestLinqToSqlId into temp + from tc in temp.DefaultIfEmpty() + where a.id == item.id + select new { a.id, bid = tc.id }).ToList(); + Assert.True(t3.Any()); + Assert.Equal(item.id, t3[0].id); + Assert.Equal(comment.id, t3[0].bid); + } - var t1 = (from a in g.sqlite.Select() - from b in g.sqlite.Select() - where a.id == b.TestLinqToSqlId - select a).ToList(); - Assert.True(t1.Any()); - //Assert.Equal(item.id, t1[0].id); + [Fact] + public void From() + { + var item = new TestLinqToSql { name = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(item).ExecuteAffrows(); + var comment = new TestLinqToSqlComment { TestLinqToSqlId = item.id, text = Guid.NewGuid().ToString() }; + g.sqlite.Insert().AppendData(comment).ExecuteAffrows(); - var t2 = (from a in g.sqlite.Select() - from b in g.sqlite.Select() - where a.id == b.TestLinqToSqlId - select new { a.id, bid = b.id }).ToList(); - Assert.True(t2.Any()); - //Assert.Equal(item.id, t2[0].id); - //Assert.Equal(comment.id, t2[0].bid); + var t1 = (from a in g.sqlite.Select() + from b in g.sqlite.Select() + where a.id == b.TestLinqToSqlId + select a).ToList(); + Assert.True(t1.Any()); + //Assert.Equal(item.id, t1[0].id); - var t3 = (from a in g.sqlite.Select() - from b in g.sqlite.Select() - where a.id == b.TestLinqToSqlId - where a.id == item.id - select new { a.id, bid = b.id }).ToList(); - Assert.True(t3.Any()); - Assert.Equal(item.id, t3[0].id); - Assert.Equal(comment.id, t3[0].bid); - } - } + var t2 = (from a in g.sqlite.Select() + from b in g.sqlite.Select() + where a.id == b.TestLinqToSqlId + select new { a.id, bid = b.id }).ToList(); + Assert.True(t2.Any()); + //Assert.Equal(item.id, t2[0].id); + //Assert.Equal(comment.id, t2[0].bid); + + var t3 = (from a in g.sqlite.Select() + from b in g.sqlite.Select() + where a.id == b.TestLinqToSqlId + where a.id == item.id + select new { a.id, bid = b.id }).ToList(); + Assert.True(t3.Any()); + Assert.Equal(item.id, t3[0].id); + Assert.Equal(comment.id, t3[0].bid); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlDeleteTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlDeleteTest.cs index d9c34893..329cb3aa 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlDeleteTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlDeleteTest.cs @@ -4,85 +4,94 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySql { - public class MySqlDeleteTest { +namespace FreeSql.Tests.MySql +{ + public class MySqlDeleteTest + { - IDelete delete => g.mysql.Delete(); //�������� + IDelete delete => g.mysql.Delete(); //�������� - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void Dywhere() { - Assert.Null(g.mysql.Delete().ToSql()); - var sql = g.mysql.Delete(new[] { 1, 2 }).ToSql(); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(g.mysql.Delete().ToSql()); + var sql = g.mysql.Delete(new[] { 1, 2 }).ToSql(); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); - sql = g.mysql.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); + sql = g.mysql.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); - sql = g.mysql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); + sql = g.mysql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1 OR `Id` = 2)", sql); - sql = g.mysql.Delete(new { id = 1 }).ToSql(); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); - } + sql = g.mysql.Delete(new { id = 1 }).ToSql(); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); + } - [Fact] - public void Where() { - var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); + [Fact] + public void Where() + { + var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); - sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql); + sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM `tb_topic` WHERE (id = @id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = delete.Where(item).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = delete.Where(item).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = delete.Where(items).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + sql = delete.Where(items).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM `tb_topic` WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - var id = g.mysql.Insert(new Topic { Title = "xxxx" }).ExecuteIdentity(); - Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); - } - [Fact] - public void ExecuteDeleted() { + var id = g.mysql.Insert(new Topic { Title = "xxxx" }).ExecuteIdentity(); + Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); + } + [Fact] + public void ExecuteDeleted() + { - //delete.Where(a => a.Id > 0).ExecuteDeleted(); - } + //delete.Where(a => a.Id > 0).ExecuteDeleted(); + } - [Fact] - public void AsTable() { - Assert.Null(g.mysql.Delete().ToSql()); - var sql = g.mysql.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); + [Fact] + public void AsTable() + { + Assert.Null(g.mysql.Delete().ToSql()); + var sql = g.mysql.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); - sql = g.mysql.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); + sql = g.mysql.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); - sql = g.mysql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); + sql = g.mysql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1 OR `Id` = 2)", sql); - sql = g.mysql.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); - } - } + sql = g.mysql.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM `TopicAsTable` WHERE (`Id` = 1)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlInsertTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlInsertTest.cs index cbfa3930..76fe633a 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlInsertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlInsertTest.cs @@ -4,133 +4,144 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySql { - public class MySqlInsertTest { +namespace FreeSql.Tests.MySql +{ + public class MySqlInsertTest + { - IInsert insert => g.mysql.Insert(); //�������� + IInsert insert => g.mysql.Insert(); //�������� - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestEnumInsertTb { - [Column(IsIdentity = true)] - public int id { get; set; } - public TestEnumInserTbType type { get; set; } - public DateTime time { get; set; } = new DateTime(); - } - enum TestEnumInserTbType { str1, biggit, sum211 } - - [Fact] - public void AppendData() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestEnumInsertTb + { + [Column(IsIdentity = true)] + public int id { get; set; } + public TestEnumInserTbType type { get; set; } + public DateTime time { get; set; } = new DateTime(); + } + enum TestEnumInserTbType { str1, biggit, sum211 } - var sql = insert.AppendData(items.First()).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql); + [Fact] + public void AppendData() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0), (?Clicks_1, ?Title_1, ?CreateTime_1), (?Clicks_2, ?Title_2, ?CreateTime_2), (?Clicks_3, ?Title_3, ?CreateTime_3), (?Clicks_4, ?Title_4, ?CreateTime_4), (?Clicks_5, ?Title_5, ?CreateTime_5), (?Clicks_6, ?Title_6, ?CreateTime_6), (?Clicks_7, ?Title_7, ?CreateTime_7), (?Clicks_8, ?Title_8, ?CreateTime_8), (?Clicks_9, ?Title_9, ?CreateTime_9)", sql); + var sql = insert.AppendData(items.First()).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql); + sql = insert.AppendData(items).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0), (?Clicks_1, ?Title_1, ?CreateTime_1), (?Clicks_2, ?Title_2, ?CreateTime_2), (?Clicks_3, ?Title_3, ?CreateTime_3), (?Clicks_4, ?Title_4, ?CreateTime_4), (?Clicks_5, ?Title_5, ?CreateTime_5), (?Clicks_6, ?Title_6, ?CreateTime_6), (?Clicks_7, ?Title_7, ?CreateTime_7), (?Clicks_8, ?Title_8, ?CreateTime_8), (?Clicks_9, ?Title_9, ?CreateTime_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql); - sql = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql(); - Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql); + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); - sql = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql(); - Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); - } + sql = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211, time = DateTime.Now }).ToSql(); + Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql); - [Fact] - public void InsertColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ToSql(); + Assert.Equal("INSERT INTO `TestEnumInsertTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); + } - var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql); + [Fact] + public void InsertColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).InsertColumns(a =>new { a.Title, a.Clicks }).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); - } - [Fact] - public void IgnoreColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql); - var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); + } + [Fact] + public void IgnoreColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); - Assert.Equal("INSERT INTO `tb_topic`(`Clicks`) VALUES(?Clicks_0), (?Clicks_1), (?Clicks_2), (?Clicks_3), (?Clicks_4), (?Clicks_5), (?Clicks_6), (?Clicks_7), (?Clicks_8), (?Clicks_9)", sql); - } - [Fact] - public void ExecuteAffrows() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); - Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); + Assert.Equal("INSERT INTO `tb_topic`(`Clicks`) VALUES(?Clicks_0), (?Clicks_1), (?Clicks_2), (?Clicks_3), (?Clicks_4), (?Clicks_5), (?Clicks_6), (?Clicks_7), (?Clicks_8), (?Clicks_9)", sql); + } + [Fact] + public void ExecuteAffrows() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - Assert.Equal(1, g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteAffrows()); - Assert.Equal(1, g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows()); - } - [Fact] - public void ExecuteIdentity() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); - Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); + Assert.Equal(1, g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteAffrows()); + Assert.Equal(1, g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteAffrows()); + } + [Fact] + public void ExecuteIdentity() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - var id = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteIdentity(); - Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select< TestEnumInsertTb>().Where(a => a.id == id).First()?.type); - id = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteIdentity(); - Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); - } - [Fact] - public void ExecuteInserted() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); - //insert.AppendData(items.First()).ExecuteInserted(); - } + var id = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).ExecuteIdentity(); + Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); + id = g.mysql.Insert().AppendData(new TestEnumInsertTb { type = TestEnumInserTbType.sum211 }).NoneParameter().ExecuteIdentity(); + Assert.Equal(TestEnumInserTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); + } + [Fact] + public void ExecuteInserted() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - [Fact] - public void AsTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + //insert.AppendData(items.First()).ExecuteInserted(); + } - var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql); + [Fact] + public void AsTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0), (?Clicks_1, ?Title_1, ?CreateTime_1), (?Clicks_2, ?Title_2, ?CreateTime_2), (?Clicks_3, ?Title_3, ?CreateTime_3), (?Clicks_4, ?Title_4, ?CreateTime_4), (?Clicks_5, ?Title_5, ?CreateTime_5), (?Clicks_6, ?Title_6, ?CreateTime_6), (?Clicks_7, ?Title_7, ?CreateTime_7), (?Clicks_8, ?Title_8, ?CreateTime_8), (?Clicks_9, ?Title_9, ?CreateTime_9)", sql); + var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql); + sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`, `CreateTime`) VALUES(?Clicks_0, ?Title_0, ?CreateTime_0), (?Clicks_1, ?Title_1, ?CreateTime_1), (?Clicks_2, ?Title_2, ?CreateTime_2), (?Clicks_3, ?Title_3, ?CreateTime_3), (?Clicks_4, ?Title_4, ?CreateTime_4), (?Clicks_5, ?Title_5, ?CreateTime_5), (?Clicks_6, ?Title_6, ?CreateTime_6), (?Clicks_7, ?Title_7, ?CreateTime_7), (?Clicks_8, ?Title_8, ?CreateTime_8), (?Clicks_9, ?Title_9, ?CreateTime_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql); + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Title`) VALUES(?Title_0), (?Title_1), (?Title_2), (?Title_3), (?Title_4), (?Title_5), (?Title_6), (?Title_7), (?Title_8), (?Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`) VALUES(?Clicks_0), (?Clicks_1), (?Clicks_2), (?Clicks_3), (?Clicks_4), (?Clicks_5), (?Clicks_6), (?Clicks_7), (?Clicks_8), (?Clicks_9)", sql); - } - } + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`, `Title`) VALUES(?Clicks_0, ?Title_0), (?Clicks_1, ?Title_1), (?Clicks_2, ?Title_2), (?Clicks_3, ?Title_3), (?Clicks_4, ?Title_4), (?Clicks_5, ?Title_5), (?Clicks_6, ?Title_6), (?Clicks_7, ?Title_7), (?Clicks_8, ?Title_8), (?Clicks_9, ?Title_9)", sql); + + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO `Topic_InsertAsTable`(`Clicks`) VALUES(?Clicks_0), (?Clicks_1), (?Clicks_2), (?Clicks_3), (?Clicks_4), (?Clicks_5), (?Clicks_6), (?Clicks_7), (?Clicks_8), (?Clicks_9)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlSelectTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlSelectTest.cs index 382dca0c..05d89b37 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlSelectTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlSelectTest.cs @@ -5,1218 +5,1297 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySql { - - public class MySqlSelectTest { - - ISelect select => g.mysql.Select(); - - [Table(Name = "tb_topic")] - public class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - [Column(OldName = "TypeGuid")] - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - - public virtual TopicFields Fields { get; set; } - } - public class TopicFields { - [Column(IsPrimary = true)] - public int TopicId { get; set; } - public virtual Topic Topic { get; set; } - } - public class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - - public int ParentId { get; set; } - public virtual TestTypeParentInfo Parent { get; set; } - - public string Name { get; set; } - - public virtual ICollection Topics { get; set; } - } - public class TestTypeParentInfo { - [Column(IsIdentity = true)] - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - - public partial class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } - - public virtual ICollection Tags { get; set; } - } - public partial class Song_tag { - public int Song_id { get; set; } - public virtual Song Song { get; set; } - - public int Tag_id { get; set; } - public virtual Tag Tag { get; set; } - } - public partial class Tag { - [Column(IsIdentity = true)] - public int Id { get; set; } - public int? Parent_id { get; set; } - public virtual Tag Parent { get; set; } - - public decimal? Ddd { get; set; } - public string Name { get; set; } - - public virtual ICollection Songs { get; set; } - public virtual ICollection Tags { get; set; } - } - - - [Fact] - public void AsSelect() { - //OneToOne、ManyToOne - var t0 = g.mysql.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 - //FROM `Tag` a - //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` - //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` - //WHERE (a__Parent__Parent.`Name` = '粤语') - - //OneToMany - var t1 = g.mysql.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` - //FROM `Tag` a - //WHERE (exists(SELECT 1 - // FROM `Tag` t - // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` - // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) - // limit 0,1)) - - //ManyToMany - var t2 = g.mysql.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); - //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` - //FROM `Song` a - //WHERE(exists(SELECT 1 - // FROM `Song_tag` Mt_Ms - // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 - // FROM `Tag` t - // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) - // limit 0, 1)) - // limit 0, 1)) - } - - [Fact] - public void Lazy() { - var tags = g.mysql.Select().Where(a => a.Parent.Name == "xxx") - .LeftJoin(a => a.Parent_id == a.Parent.Id) - .ToSql(); - - var songs = g.mysql.Select().Limit(10).ToList(); - } - - [Fact] - public void ToDataTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - - Assert.Equal(1, g.mysql.Insert().AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, g.mysql.Insert().AppendData(items).ExecuteAffrows()); - - //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - //Assert.Equal(9989, g.mysql.Insert(items).ExecuteAffrows()); - - var dt1 = select.Limit(10).ToDataTable(); - var dt2 = select.Limit(10).ToDataTable("id, 111222"); - var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); - } - - class TestDto { - public int id { get; set; } - public string name { get; set; } //这是join表的属性 - public int ParentId { get; set; } //这是join表的属性 - } - [Fact] - public void ToList() { - - var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto2 = select.Limit(10).ToList(a => new TestDto()); - var testDto3 = select.Limit(10).ToList(a => new TestDto { }); - var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); - var testDto5 = select.Limit(10).ToList(); - - var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); - var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); - var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); - var testDto55 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(); - - var t0 = select.Limit(50).ToList(); - - - var t1 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); - var t2 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); - - - var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToSql(); - var sql2 = select.LeftJoin((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToSql(); - var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToSql(); - - //g.mysql.Select().Join((a, b, c) => new Model.JoinResult3( - // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, - // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") - //); - - //var sql4 = select.From((a, b, c) => new SelectFrom() - // .InnerJoin(a.TypeGuid == b.Guid) - // .LeftJoin(c.Id == b.ParentId) - // .Where(b.Name == "xxx")) - //.Where(a => a.Id == 1).ToSql(); - - var sql4 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => c.Id == b.ParentId) - .Where(a => b.Name == "xxx")).ToSql(); - //.Where(a => a.Id == 1).ToSql(); - - - var list111 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => c.Id == b.ParentId) - .Where(a => b.Name != "xxx")); - var list111sql = list111.ToSql(); - var list111data = list111.ToList((a, b, c) => new { - a.Id, - title_substring = a.Title.Substring(0, 1), - a.Type, - ccc = new { a.Id, a.Title }, - tp = a.Type, - tp2 = new { - a.Id, - tp2 = a.Type.Name - }, - tp3 = new { - a.Id, - tp33 = new { - a.Id - } - } - }); - - var ttt122 = g.mysql.Select().Where(a => a.Id > 0).ToSql(); - var sql5 = g.mysql.Select().From((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToSql(); - var t11112 = g.mysql.Select().ToList(a => new { - a.Id, - a.Title, - a.Type, - ccc = new { a.Id, a.Title }, - tp = a.Type, - tp2 = new { - a.Id, - tp2 = a.Type.Name - }, - tp3 = new { - a.Id, - tp33 = new { - a.Id - } - } - - }); - - var t100 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - var t101 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - - - var t1111 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type }); - - var t2222 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type.Name }); - - g.mysql.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); - var testGuidId5 = g.mysql.Select().ToList(); - var testGuidId6 = g.mysql.Select().ToList(a => a.id); - - var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); - var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); - } - class TestGuidIdToList { - public Guid id { get; set; } - public string title { get; set; } = Guid.NewGuid().ToString(); - } - [Fact] - public void ToOne() { - var testnotfind = select.Where("1=2").First(a => a.CreateTime); - Assert.Equal(default(DateTime), testnotfind); - } - [Fact] - public void ToSql() { - g.mysql.Insert().AppendData(new testenumWhere { type = testenumWhereType.Blaaa }).ExecuteAffrows(); - - var sql1 = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToSql(); - var sql2 = g.mysql.Select().Where(a => testenumWhereType.Blaaa == a.type).ToSql(); - - var sql3 = g.mysql.Select().Where(a => a.type.Equals(testenumWhereType.Blaaa)).ToSql(); - var tolist = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToList(); - } - class testenumWhere { - public Guid id { get; set; } - public testenumWhereType type { get; set; } - } - public enum testenumWhereType { Menu, Class, Blaaa } - - [Fact] - public void Any() { - var count = select.Where(a => 1 == 1).Count(); - Assert.False(select.Where(a => 1 == 2).Any()); - Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); - - var sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && - select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - //.Offset(a.Id) - .Any() - ).Any(c => c.Id == a.Id + 10) - ); - var sql2222Tolist = sql2222.ToList(); - - var collectionSelect = select.Where(a => - a.Type.Guid == a.TypeGuid && - a.Type.Parent.Id == a.Type.ParentId && - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) - ); - collectionSelect.ToList(); - } - [Fact] - public void Count() { - var count = select.Where(a => 1 == 1).Count(); - select.Where(a => 1 == 1).Count(out var count2); - Assert.Equal(count, count2); - Assert.Equal(0, select.Where(a => 1 == 2).Count()); - } - [Fact] - public void Master() { - Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); - } - [Fact] - public void From() { - var query2 = select.From((s, b) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - ); - var sql2 = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid`", sql2); - query2.ToList(); - - var query3 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id) - ); - var sql3 = query3.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql3); - query3.ToList(); - } - [Fact] - public void LeftJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", sql); - query.ToList(); - } - [Fact] - public void InnerJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //������� - query = select - .InnerJoin(a => a.Type.Guid == a.TypeGuid) - .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` INNER JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - query = select - .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .InnerJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` INNER JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .InnerJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` INNER JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", sql); - query.ToList(); - - } - [Fact] - public void RightJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); - query.ToList(); - - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - query.ToList(); - - //������� - query = select - .RightJoin(a => a.Type.Guid == a.TypeGuid) - .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` RIGHT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - query = select - .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .RightJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` RIGHT JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .RightJoin(a => a.TypeGuid == b.Guid) - .RightJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` RIGHT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", sql); - query.ToList(); - - } - [Fact] - public void Where() { - - var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); - var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); - var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); - - var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.Where(a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10)", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE ((a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100))", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10) AND (a.`Clicks` > 100)", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle')", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle' AND a__Type.`Guid` = a.`TypeGuid`)", sql); - query.ToList(); - - query = select.Where(a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Name` = 'tparent')", sql); - query.ToList(); - - //���û�е������ԣ��򵥶������ - query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b WHERE (b.`Guid` = a.`TypeGuid` AND b.`Name` = 'typeTitle')", sql); - query.ToList(); - - query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b WHERE (b.`Name` = 'typeTitle' AND b.`Guid` = a.`TypeGuid`)", sql); - query.ToList(); - - query = select.Where((a, b, c) => c.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeParentInfo` c WHERE (c.`Name` = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .Where(a => a.Id == 10 && c.Name == "xxx") - .Where(a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c WHERE (a.`Id` = 10 AND c.`Name` = 'xxx') AND (b.`ParentId` = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.Where("a.clicks > 100 and a.id = ?id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.clicks > 100 and a.id = ?id)", sql); - query.ToList(); - } - [Fact] - public void WhereIf() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.WhereIf(true, a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE ((a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100))", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10) AND (a.`Clicks` > 100)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle')", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle' AND a__Type.`Guid` = a.`TypeGuid`)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Name` = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(true, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c WHERE (a.`Id` = 10 AND c.`Name` = 'xxx') AND (b.`ParentId` = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(true, "a.clicks > 100 and a.id = ?id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.clicks > 100 and a.id = ?id)", sql); - query.ToList(); - - // ==========================================WhereIf(false) - - //����е�������a.Type��a.Type.Parent ���ǵ������� - query = select.WhereIf(false, a => a.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - query2 = select.From((s, b, c) => s - .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(false, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(false, "a.clicks > 100 and a.id = ?id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); - query.ToList(); - } - [Fact] - public void WhereExists() { - var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); - - sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - - //.Offset(a.Id) - - .Any() - ).Any() - ).ToList(); - } - [Fact] - public void GroupBy() { - var groupby = select.From((s, b, c) => s - .Where(a => a.Id == 1) - ) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()) - .Offset(10) - .Limit(2) - .ToList(a => new { - a.Key.tt2, - cou1 = a.Count(), - arg1 = a.Avg(a.Key.mod4), - ccc2 = a.Key.tt2 ?? "now()", - //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") - ccc3 = a.Max(a.Value.Item3.Id) - }); - - var testpid1 = g.mysql.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); - g.mysql.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); - - var aggsql1 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist1 = select - .GroupBy(a => a.Title) - .ToList(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToSql(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToList(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql3 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid), - sum3 = b.Sum(b.Value.Type.Parent.Id) - }); - } - [Fact] - public void ToAggregate() { - var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); - } - - [Fact] - public void OrderBy() { - var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); - } - [Fact] - public void Skip_Offset() { - var sql = select.Offset(10).Limit(10).ToList(); - } - [Fact] - public void Take_Limit() { - var sql = select.Limit(10).ToList(); - } - [Fact] - public void Page() { - var sql1 = select.Page(1, 10).ToList(); - var sql2 = select.Page(2, 10).ToList(); - var sql3 = select.Page(3, 10).ToList(); - - var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); - var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); - var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); - } - [Fact] - public void Distinct() { - var t1 = select.Distinct().ToList(a => a.Title); - var t2 = select.Distinct().Limit(10).ToList(a => a.Title); - } - - [Fact] - public void Sum() { - } - [Fact] - public void Min() { - } - [Fact] - public void Max() { - } - [Fact] - public void Avg() { - } - [Fact] - public void As() { - } - - [Fact] - public void AsTable() { - - var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); - - Func tableRule = (type, oldname) => { - if (type == typeof(Topic)) return oldname + "AsTable1"; - else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; - return oldname + "AsTable"; - }; - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid`", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); - - query = select - .LeftJoin((a, b) => b.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` c ON c.`Id` = a__Type.`ParentId`", sql); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfoAsTable` c ON b.`ParentId` = c.`Id`", sql); - - //������϶����㲻�� - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", new { bname = "xxx" }).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", sql); - } - - public class TestInclude_OneToManyModel1 { - [Column(IsIdentity = true)] - public int id { get; set; } - public virtual TestInclude_OneToManyModel2 model2 { get; set; } - - public string m1name { get; set; } - } - public class TestInclude_OneToManyModel2 { - [Column(IsPrimary = true)] - public int model2id { get; set; } - public virtual TestInclude_OneToManyModel1 model1 { get; set; } - - public string m2setting { get; set; } - - public List childs { get; set; } - } - public class TestInclude_OneToManyModel3 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model2111Idaaa { get; set; } - public string title { get; set; } - - public List childs2 { get; set; } - } - public class TestInclude_OneToManyModel4 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model3333Id333 { get; set; } - public string title444 { get; set; } - } - - [Fact] - public void Include_OneToMany() { - var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; - model1.id = (int)g.mysql.Insert(model1).ExecuteIdentity(); - var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; - g.mysql.Insert(model2).ExecuteAffrows(); - - var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; - model3_1.id = (int)g.mysql.Insert(model3_1).ExecuteIdentity(); - var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; - model3_2.id = (int)g.mysql.Insert(model3_2).ExecuteIdentity(); - var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; - model3_3.id = (int)g.mysql.Insert(model3_2).ExecuteIdentity(); - - var model4s = new[] { - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } - }; - Assert.Equal(5, g.mysql.Insert(model4s).ExecuteAffrows()); - - var t0 = g.mysql.Select() - .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t1 = g.mysql.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t2 = g.mysql.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - - var t00 = g.mysql.Select() - .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t11 = g.mysql.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t22 = g.mysql.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - } - - public class TestInclude_OneToManyModel11 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2id { get; set; } - public string m3setting { get; set; } - public TestInclude_OneToManyModel22 model2 { get; set; } - public string m1name { get; set; } - } - - public class TestInclude_OneToManyModel22 { - [Column(IsIdentity = true)] - public int id { get; set; } - public string m2setting { get; set; } - public List childs { get; set; } - } - public class TestInclude_OneToManyModel33 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2Id { get; set; } - public string title { get; set; } - public string setting { get; set; } - } - [Fact] - public void Include_OneToMany2() { - string setting = "x"; - var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; - model2.id = (int)g.mysql.Insert(model2).ExecuteIdentity(); - - var model3s = new[] - { - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} - }; - Assert.Equal(3, g.mysql.Insert(model3s).ExecuteAffrows()); - - var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; - model1.id = (int)g.mysql.Insert(model1).ExecuteIdentity(); - - var t1 = g.mysql.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - - var t11 = g.mysql.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - } - - [Fact] - public void Include_OneToChilds() { - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_中国" - }; - tag1.Id = (int)g.mysql.Insert(tag1).ExecuteIdentity(); - var tag1_1 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_北京" - }; - tag1_1.Id = (int)g.mysql.Insert(tag1_1).ExecuteIdentity(); - var tag1_2 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_上海" - }; - tag1_2.Id = (int)g.mysql.Insert(tag1_2).ExecuteIdentity(); - - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_美国" - }; - tag2.Id = (int)g.mysql.Insert(tag2).ExecuteIdentity(); - var tag2_1 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_纽约" - }; - tag2_1.Id = (int)g.mysql.Insert(tag2_1).ExecuteIdentity(); - var tag2_2 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_华盛顿" - }; - tag2_2.Id = (int)g.mysql.Insert(tag2_2).ExecuteIdentity(); - - var tags0 = g.mysql.Select() - .Include(a => a.Parent) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags1 = g.mysql.Select() - .IncludeMany(a => a.Tags) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags2 = g.mysql.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags3 = g.mysql.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags11 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags22 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags33 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - } - - [Fact] - public void Include_ManyToMany() { - - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_01_中国" - }; - tag1.Id = (int)g.mysql.Insert(tag1).ExecuteIdentity(); - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_02_美国" - }; - tag2.Id = (int)g.mysql.Insert(tag2).ExecuteIdentity(); - var tag3 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_03_日本" - }; - tag3.Id = (int)g.mysql.Insert(tag3).ExecuteIdentity(); - - var song1 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_01_我是中国人.mp3", - Url = "http://ww.baidu.com/" - }; - song1.Id = (int)g.mysql.Insert(song1).ExecuteIdentity(); - var song2 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_02_爱你一万年.mp3", - Url = "http://ww.163.com/" - }; - song2.Id = (int)g.mysql.Insert(song2).ExecuteIdentity(); - var song3 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_03_千年等一回.mp3", - Url = "http://ww.sina.com/" - }; - song3.Id = (int)g.mysql.Insert(song3).ExecuteIdentity(); - - g.mysql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); - - var songs1 = g.mysql.Select() - .IncludeMany(a => a.Tags) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs1.Count); - Assert.Equal(2, songs1[0].Tags.Count); - Assert.Equal(1, songs1[1].Tags.Count); - Assert.Equal(3, songs1[2].Tags.Count); - - var songs2 = g.mysql.Select() - .IncludeMany(a => a.Tags, - then => then.IncludeMany(t => t.Songs)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs2.Count); - Assert.Equal(2, songs2[0].Tags.Count); - Assert.Equal(1, songs2[1].Tags.Count); - Assert.Equal(3, songs2[2].Tags.Count); - - var tags3 = g.mysql.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - - - var songs11 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs11.Count); - Assert.Equal(1, songs11[0].Tags.Count); - Assert.Equal(1, songs11[1].Tags.Count); - Assert.Equal(1, songs11[2].Tags.Count); - - var songs22 = g.mysql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.IncludeMany(t => t.Songs.Take(1))) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs22.Count); - Assert.Equal(1, songs22[0].Tags.Count); - Assert.Equal(1, songs22[1].Tags.Count); - Assert.Equal(1, songs22[2].Tags.Count); - - var tags33 = g.mysql.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs.Take(1)) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - } - } +namespace FreeSql.Tests.MySql +{ + + public class MySqlSelectTest + { + + ISelect select => g.mysql.Select(); + + [Table(Name = "tb_topic")] + public class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + [Column(OldName = "TypeGuid")] + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + + public virtual TopicFields Fields { get; set; } + } + public class TopicFields + { + [Column(IsPrimary = true)] + public int TopicId { get; set; } + public virtual Topic Topic { get; set; } + } + public class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + + public int ParentId { get; set; } + public virtual TestTypeParentInfo Parent { get; set; } + + public string Name { get; set; } + + public virtual ICollection Topics { get; set; } + } + public class TestTypeParentInfo + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + + public partial class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } + + public virtual ICollection Tags { get; set; } + } + public partial class Song_tag + { + public int Song_id { get; set; } + public virtual Song Song { get; set; } + + public int Tag_id { get; set; } + public virtual Tag Tag { get; set; } + } + public partial class Tag + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public int? Parent_id { get; set; } + public virtual Tag Parent { get; set; } + + public decimal? Ddd { get; set; } + public string Name { get; set; } + + public virtual ICollection Songs { get; set; } + public virtual ICollection Tags { get; set; } + } + + + [Fact] + public void AsSelect() + { + //OneToOne、ManyToOne + var t0 = g.mysql.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 + //FROM `Tag` a + //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` + //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` + //WHERE (a__Parent__Parent.`Name` = '粤语') + + //OneToMany + var t1 = g.mysql.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` + //FROM `Tag` a + //WHERE (exists(SELECT 1 + // FROM `Tag` t + // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` + // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) + // limit 0,1)) + + //ManyToMany + var t2 = g.mysql.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); + //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` + //FROM `Song` a + //WHERE(exists(SELECT 1 + // FROM `Song_tag` Mt_Ms + // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 + // FROM `Tag` t + // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) + // limit 0, 1)) + // limit 0, 1)) + } + + [Fact] + public void Lazy() + { + var tags = g.mysql.Select().Where(a => a.Parent.Name == "xxx") + .LeftJoin(a => a.Parent_id == a.Parent.Id) + .ToSql(); + + var songs = g.mysql.Select().Limit(10).ToList(); + } + + [Fact] + public void ToDataTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + + Assert.Equal(1, g.mysql.Insert().AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, g.mysql.Insert().AppendData(items).ExecuteAffrows()); + + //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + //Assert.Equal(9989, g.mysql.Insert(items).ExecuteAffrows()); + + var dt1 = select.Limit(10).ToDataTable(); + var dt2 = select.Limit(10).ToDataTable("id, 111222"); + var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); + } + + class TestDto + { + public int id { get; set; } + public string name { get; set; } //这是join表的属性 + public int ParentId { get; set; } //这是join表的属性 + } + [Fact] + public void ToList() + { + + var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto2 = select.Limit(10).ToList(a => new TestDto()); + var testDto3 = select.Limit(10).ToList(a => new TestDto { }); + var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); + var testDto5 = select.Limit(10).ToList(); + + var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); + var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); + var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); + var testDto55 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(); + + var t0 = select.Limit(50).ToList(); + + + var t1 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); + var t2 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); + + + var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToSql(); + var sql2 = select.LeftJoin((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToSql(); + var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToSql(); + + //g.mysql.Select().Join((a, b, c) => new Model.JoinResult3( + // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, + // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") + //); + + //var sql4 = select.From((a, b, c) => new SelectFrom() + // .InnerJoin(a.TypeGuid == b.Guid) + // .LeftJoin(c.Id == b.ParentId) + // .Where(b.Name == "xxx")) + //.Where(a => a.Id == 1).ToSql(); + + var sql4 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => c.Id == b.ParentId) + .Where(a => b.Name == "xxx")).ToSql(); + //.Where(a => a.Id == 1).ToSql(); + + + var list111 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => c.Id == b.ParentId) + .Where(a => b.Name != "xxx")); + var list111sql = list111.ToSql(); + var list111data = list111.ToList((a, b, c) => new + { + a.Id, + title_substring = a.Title.Substring(0, 1), + a.Type, + ccc = new { a.Id, a.Title }, + tp = a.Type, + tp2 = new + { + a.Id, + tp2 = a.Type.Name + }, + tp3 = new + { + a.Id, + tp33 = new + { + a.Id + } + } + }); + + var ttt122 = g.mysql.Select().Where(a => a.Id > 0).ToSql(); + var sql5 = g.mysql.Select().From((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToSql(); + var t11112 = g.mysql.Select().ToList(a => new + { + a.Id, + a.Title, + a.Type, + ccc = new { a.Id, a.Title }, + tp = a.Type, + tp2 = new + { + a.Id, + tp2 = a.Type.Name + }, + tp3 = new + { + a.Id, + tp33 = new + { + a.Id + } + } + + }); + + var t100 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + var t101 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + + + var t1111 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type }); + + var t2222 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type.Name }); + + g.mysql.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); + var testGuidId5 = g.mysql.Select().ToList(); + var testGuidId6 = g.mysql.Select().ToList(a => a.id); + + var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); + var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); + } + class TestGuidIdToList + { + public Guid id { get; set; } + public string title { get; set; } = Guid.NewGuid().ToString(); + } + [Fact] + public void ToOne() + { + var testnotfind = select.Where("1=2").First(a => a.CreateTime); + Assert.Equal(default(DateTime), testnotfind); + } + [Fact] + public void ToSql() + { + g.mysql.Insert().AppendData(new testenumWhere { type = testenumWhereType.Blaaa }).ExecuteAffrows(); + + var sql1 = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToSql(); + var sql2 = g.mysql.Select().Where(a => testenumWhereType.Blaaa == a.type).ToSql(); + + var sql3 = g.mysql.Select().Where(a => a.type.Equals(testenumWhereType.Blaaa)).ToSql(); + var tolist = g.mysql.Select().Where(a => a.type == testenumWhereType.Blaaa).ToList(); + } + class testenumWhere + { + public Guid id { get; set; } + public testenumWhereType type { get; set; } + } + public enum testenumWhereType { Menu, Class, Blaaa } + + [Fact] + public void Any() + { + var count = select.Where(a => 1 == 1).Count(); + Assert.False(select.Where(a => 1 == 2).Any()); + Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); + + var sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && + select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + //.Offset(a.Id) + .Any() + ).Any(c => c.Id == a.Id + 10) + ); + var sql2222Tolist = sql2222.ToList(); + + var collectionSelect = select.Where(a => + a.Type.Guid == a.TypeGuid && + a.Type.Parent.Id == a.Type.ParentId && + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) + ); + collectionSelect.ToList(); + } + [Fact] + public void Count() + { + var count = select.Where(a => 1 == 1).Count(); + select.Where(a => 1 == 1).Count(out var count2); + Assert.Equal(count, count2); + Assert.Equal(0, select.Where(a => 1 == 2).Count()); + } + [Fact] + public void Master() + { + Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); + } + [Fact] + public void From() + { + var query2 = select.From((s, b) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + ); + var sql2 = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid`", sql2); + query2.ToList(); + + var query3 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id) + ); + var sql3 = query3.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql3); + query3.ToList(); + } + [Fact] + public void LeftJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", sql); + query.ToList(); + } + [Fact] + public void InnerJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //������� + query = select + .InnerJoin(a => a.Type.Guid == a.TypeGuid) + .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` INNER JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + query = select + .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .InnerJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` INNER JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .InnerJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` INNER JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", sql); + query.ToList(); + + } + [Fact] + public void RightJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid`", sql); + query.ToList(); + + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + query.ToList(); + + //������� + query = select + .RightJoin(a => a.Type.Guid == a.TypeGuid) + .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` RIGHT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + query = select + .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .RightJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` RIGHT JOIN `TestTypeParentInfo` c ON c.`Id` = a__Type.`ParentId`", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .RightJoin(a => a.TypeGuid == b.Guid) + .RightJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN `TestTypeInfo` b ON a.`TypeGuid` = b.`Guid` RIGHT JOIN `TestTypeParentInfo` c ON b.`ParentId` = c.`Id`", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", sql); + query.ToList(); + + } + [Fact] + public void Where() + { + + var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); + var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); + var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); + + var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.Where(a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10)", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE ((a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100))", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10) AND (a.`Clicks` > 100)", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle')", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle' AND a__Type.`Guid` = a.`TypeGuid`)", sql); + query.ToList(); + + query = select.Where(a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Name` = 'tparent')", sql); + query.ToList(); + + //���û�е������ԣ��򵥶������ + query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b WHERE (b.`Guid` = a.`TypeGuid` AND b.`Name` = 'typeTitle')", sql); + query.ToList(); + + query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b WHERE (b.`Name` = 'typeTitle' AND b.`Guid` = a.`TypeGuid`)", sql); + query.ToList(); + + query = select.Where((a, b, c) => c.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeParentInfo` c WHERE (c.`Name` = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .Where(a => a.Id == 10 && c.Name == "xxx") + .Where(a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c WHERE (a.`Id` = 10 AND c.`Name` = 'xxx') AND (b.`ParentId` = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.Where("a.clicks > 100 and a.id = ?id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.clicks > 100 and a.id = ?id)", sql); + query.ToList(); + } + [Fact] + public void WhereIf() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.WhereIf(true, a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE ((a.`Id` = 10 AND a.`Id` > 10 OR a.`Clicks` > 100))", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.`Id` = 10) AND (a.`Clicks` > 100)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle')", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` WHERE (a__Type.`Name` = 'typeTitle' AND a__Type.`Guid` = a.`TypeGuid`)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topic` a LEFT JOIN `TestTypeInfo` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfo` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Name` = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(true, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c WHERE (a.`Id` = 10 AND c.`Name` = 'xxx') AND (b.`ParentId` = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(true, "a.clicks > 100 and a.id = ?id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a WHERE (a.clicks > 100 and a.id = ?id)", sql); + query.ToList(); + + // ==========================================WhereIf(false) + + //����е�������a.Type��a.Type.Parent ���ǵ������� + query = select.WhereIf(false, a => a.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + query2 = select.From((s, b, c) => s + .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(false, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a, `TestTypeInfo` b, `TestTypeParentInfo` c", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(false, "a.clicks > 100 and a.id = ?id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topic` a", sql); + query.ToList(); + } + [Fact] + public void WhereExists() + { + var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); + + sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + + //.Offset(a.Id) + + .Any() + ).Any() + ).ToList(); + } + [Fact] + public void GroupBy() + { + var groupby = select.From((s, b, c) => s + .Where(a => a.Id == 1) + ) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()) + .Offset(10) + .Limit(2) + .ToList(a => new + { + a.Key.tt2, + cou1 = a.Count(), + arg1 = a.Avg(a.Key.mod4), + ccc2 = a.Key.tt2 ?? "now()", + //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") + ccc3 = a.Max(a.Value.Item3.Id) + }); + + var testpid1 = g.mysql.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); + g.mysql.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); + + var aggsql1 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist1 = select + .GroupBy(a => a.Title) + .ToList(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToSql(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToList(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql3 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid), + sum3 = b.Sum(b.Value.Type.Parent.Id) + }); + } + [Fact] + public void ToAggregate() + { + var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); + } + + [Fact] + public void OrderBy() + { + var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); + } + [Fact] + public void Skip_Offset() + { + var sql = select.Offset(10).Limit(10).ToList(); + } + [Fact] + public void Take_Limit() + { + var sql = select.Limit(10).ToList(); + } + [Fact] + public void Page() + { + var sql1 = select.Page(1, 10).ToList(); + var sql2 = select.Page(2, 10).ToList(); + var sql3 = select.Page(3, 10).ToList(); + + var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); + var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); + var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); + } + [Fact] + public void Distinct() + { + var t1 = select.Distinct().ToList(a => a.Title); + var t2 = select.Distinct().Limit(10).ToList(a => a.Title); + } + + [Fact] + public void Sum() + { + } + [Fact] + public void Min() + { + } + [Fact] + public void Max() + { + } + [Fact] + public void Avg() + { + } + [Fact] + public void As() + { + } + + [Fact] + public void AsTable() + { + + var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); + + Func tableRule = (type, oldname) => + { + if (type == typeof(Topic)) return oldname + "AsTable1"; + else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; + return oldname + "AsTable"; + }; + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid`", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx'", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` AND a__Type.`Name` = 'xxx' LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid`", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx'", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` AND b.`Name` = 'xxx' LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId` WHERE (a__Type__Parent.`Id` = 10)", sql); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a__Type.`Guid`, a__Type.`ParentId`, a__Type.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` a__Type__Parent ON a__Type__Parent.`Id` = a__Type.`ParentId`", sql); + + query = select + .LeftJoin((a, b) => b.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` a__Type ON a__Type.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeInfoAsTable2` b ON b.`Guid` = a.`TypeGuid` LEFT JOIN `TestTypeParentInfoAsTable` c ON c.`Id` = a__Type.`ParentId`", sql); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, b.`Guid`, b.`ParentId`, b.`Name`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN `TestTypeInfoAsTable2` b ON a.`TypeGuid` = b.`Guid` LEFT JOIN `TestTypeParentInfoAsTable` c ON b.`ParentId` = c.`Id`", sql); + + //������϶����㲻�� + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", new { bname = "xxx" }).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime` FROM `tb_topicAsTable1` a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = ?bname", sql); + } + + public class TestInclude_OneToManyModel1 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public virtual TestInclude_OneToManyModel2 model2 { get; set; } + + public string m1name { get; set; } + } + public class TestInclude_OneToManyModel2 + { + [Column(IsPrimary = true)] + public int model2id { get; set; } + public virtual TestInclude_OneToManyModel1 model1 { get; set; } + + public string m2setting { get; set; } + + public List childs { get; set; } + } + public class TestInclude_OneToManyModel3 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model2111Idaaa { get; set; } + public string title { get; set; } + + public List childs2 { get; set; } + } + public class TestInclude_OneToManyModel4 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model3333Id333 { get; set; } + public string title444 { get; set; } + } + + [Fact] + public void Include_OneToMany() + { + var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; + model1.id = (int)g.mysql.Insert(model1).ExecuteIdentity(); + var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; + g.mysql.Insert(model2).ExecuteAffrows(); + + var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; + model3_1.id = (int)g.mysql.Insert(model3_1).ExecuteIdentity(); + var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; + model3_2.id = (int)g.mysql.Insert(model3_2).ExecuteIdentity(); + var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; + model3_3.id = (int)g.mysql.Insert(model3_2).ExecuteIdentity(); + + var model4s = new[] { + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } + }; + Assert.Equal(5, g.mysql.Insert(model4s).ExecuteAffrows()); + + var t0 = g.mysql.Select() + .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t1 = g.mysql.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t2 = g.mysql.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + + var t00 = g.mysql.Select() + .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t11 = g.mysql.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t22 = g.mysql.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + } + + public class TestInclude_OneToManyModel11 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2id { get; set; } + public string m3setting { get; set; } + public TestInclude_OneToManyModel22 model2 { get; set; } + public string m1name { get; set; } + } + + public class TestInclude_OneToManyModel22 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public string m2setting { get; set; } + public List childs { get; set; } + } + public class TestInclude_OneToManyModel33 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2Id { get; set; } + public string title { get; set; } + public string setting { get; set; } + } + [Fact] + public void Include_OneToMany2() + { + string setting = "x"; + var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; + model2.id = (int)g.mysql.Insert(model2).ExecuteIdentity(); + + var model3s = new[] + { + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} + }; + Assert.Equal(3, g.mysql.Insert(model3s).ExecuteAffrows()); + + var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; + model1.id = (int)g.mysql.Insert(model1).ExecuteIdentity(); + + var t1 = g.mysql.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + + var t11 = g.mysql.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + } + + [Fact] + public void Include_OneToChilds() + { + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_中国" + }; + tag1.Id = (int)g.mysql.Insert(tag1).ExecuteIdentity(); + var tag1_1 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_北京" + }; + tag1_1.Id = (int)g.mysql.Insert(tag1_1).ExecuteIdentity(); + var tag1_2 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_上海" + }; + tag1_2.Id = (int)g.mysql.Insert(tag1_2).ExecuteIdentity(); + + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_美国" + }; + tag2.Id = (int)g.mysql.Insert(tag2).ExecuteIdentity(); + var tag2_1 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_纽约" + }; + tag2_1.Id = (int)g.mysql.Insert(tag2_1).ExecuteIdentity(); + var tag2_2 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_华盛顿" + }; + tag2_2.Id = (int)g.mysql.Insert(tag2_2).ExecuteIdentity(); + + var tags0 = g.mysql.Select() + .Include(a => a.Parent) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags1 = g.mysql.Select() + .IncludeMany(a => a.Tags) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags2 = g.mysql.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags3 = g.mysql.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags11 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags22 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags33 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + } + + [Fact] + public void Include_ManyToMany() + { + + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_01_中国" + }; + tag1.Id = (int)g.mysql.Insert(tag1).ExecuteIdentity(); + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_02_美国" + }; + tag2.Id = (int)g.mysql.Insert(tag2).ExecuteIdentity(); + var tag3 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_03_日本" + }; + tag3.Id = (int)g.mysql.Insert(tag3).ExecuteIdentity(); + + var song1 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_01_我是中国人.mp3", + Url = "http://ww.baidu.com/" + }; + song1.Id = (int)g.mysql.Insert(song1).ExecuteIdentity(); + var song2 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_02_爱你一万年.mp3", + Url = "http://ww.163.com/" + }; + song2.Id = (int)g.mysql.Insert(song2).ExecuteIdentity(); + var song3 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_03_千年等一回.mp3", + Url = "http://ww.sina.com/" + }; + song3.Id = (int)g.mysql.Insert(song3).ExecuteIdentity(); + + g.mysql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.mysql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); + + var songs1 = g.mysql.Select() + .IncludeMany(a => a.Tags) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs1.Count); + Assert.Equal(2, songs1[0].Tags.Count); + Assert.Equal(1, songs1[1].Tags.Count); + Assert.Equal(3, songs1[2].Tags.Count); + + var songs2 = g.mysql.Select() + .IncludeMany(a => a.Tags, + then => then.IncludeMany(t => t.Songs)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs2.Count); + Assert.Equal(2, songs2[0].Tags.Count); + Assert.Equal(1, songs2[1].Tags.Count); + Assert.Equal(3, songs2[2].Tags.Count); + + var tags3 = g.mysql.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + + + var songs11 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs11.Count); + Assert.Equal(1, songs11[0].Tags.Count); + Assert.Equal(1, songs11[1].Tags.Count); + Assert.Equal(1, songs11[2].Tags.Count); + + var songs22 = g.mysql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.IncludeMany(t => t.Songs.Take(1))) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs22.Count); + Assert.Equal(1, songs22[0].Tags.Count); + Assert.Equal(1, songs22[1].Tags.Count); + Assert.Equal(1, songs22[2].Tags.Count); + + var tags33 = g.mysql.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs.Take(1)) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlUpdateTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlUpdateTest.cs index 95f65f3f..55808901 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlUpdateTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/Curd/MySqlUpdateTest.cs @@ -3,185 +3,200 @@ using System; using System.Collections.Generic; using Xunit; -namespace FreeSql.Tests.MySql { - public class MySqlUpdateTest { - IUpdate update => g.mysql.Update(); +namespace FreeSql.Tests.MySql +{ + public class MySqlUpdateTest + { + IUpdate update => g.mysql.Update(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestEnumUpdateTb { - [Column(IsIdentity = true)] - public int id { get; set; } - public TestEnumUpdateTbType type { get; set; } - public DateTime time { get; set; } = new DateTime(); - } - enum TestEnumUpdateTbType { str1, biggit, sum211 } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestEnumUpdateTb + { + [Column(IsIdentity = true)] + public int id { get; set; } + public TestEnumUpdateTbType type { get; set; } + public DateTime time { get; set; } = new DateTime(); + } + enum TestEnumUpdateTbType { str1, biggit, sum211 } - [Fact] - public void Dywhere() { - Assert.Null(g.mysql.Update().ToSql()); - Assert.Equal("UPDATE `tb_topic` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); - Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); - } + [Fact] + public void Dywhere() + { + Assert.Null(g.mysql.Update().ToSql()); + Assert.Equal("UPDATE `tb_topic` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); + Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE `tb_topic` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); + } - [Fact] - public void SetSource() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ?p_0, `Title` = ?p_1, `CreateTime` = ?p_2 WHERE (`Id` = 1)", sql); + [Fact] + public void SetSource() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ?p_0, `Title` = ?p_1, `CreateTime` = ?p_2 WHERE (`Id` = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.SetSource(items).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = CASE `Id` WHEN 1 THEN ?p_0 WHEN 2 THEN ?p_1 WHEN 3 THEN ?p_2 WHEN 4 THEN ?p_3 WHEN 5 THEN ?p_4 WHEN 6 THEN ?p_5 WHEN 7 THEN ?p_6 WHEN 8 THEN ?p_7 WHEN 9 THEN ?p_8 WHEN 10 THEN ?p_9 END, `Title` = CASE `Id` WHEN 1 THEN ?p_10 WHEN 2 THEN ?p_11 WHEN 3 THEN ?p_12 WHEN 4 THEN ?p_13 WHEN 5 THEN ?p_14 WHEN 6 THEN ?p_15 WHEN 7 THEN ?p_16 WHEN 8 THEN ?p_17 WHEN 9 THEN ?p_18 WHEN 10 THEN ?p_19 END, `CreateTime` = CASE `Id` WHEN 1 THEN ?p_20 WHEN 2 THEN ?p_21 WHEN 3 THEN ?p_22 WHEN 4 THEN ?p_23 WHEN 5 THEN ?p_24 WHEN 6 THEN ?p_25 WHEN 7 THEN ?p_26 WHEN 8 THEN ?p_27 WHEN 9 THEN ?p_28 WHEN 10 THEN ?p_29 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = CASE `Id` WHEN 1 THEN ?p_0 WHEN 2 THEN ?p_1 WHEN 3 THEN ?p_2 WHEN 4 THEN ?p_3 WHEN 5 THEN ?p_4 WHEN 6 THEN ?p_5 WHEN 7 THEN ?p_6 WHEN 8 THEN ?p_7 WHEN 9 THEN ?p_8 WHEN 10 THEN ?p_9 END, `Title` = CASE `Id` WHEN 1 THEN ?p_10 WHEN 2 THEN ?p_11 WHEN 3 THEN ?p_12 WHEN 4 THEN ?p_13 WHEN 5 THEN ?p_14 WHEN 6 THEN ?p_15 WHEN 7 THEN ?p_16 WHEN 8 THEN ?p_17 WHEN 9 THEN ?p_18 WHEN 10 THEN ?p_19 END, `CreateTime` = CASE `Id` WHEN 1 THEN ?p_20 WHEN 2 THEN ?p_21 WHEN 3 THEN ?p_22 WHEN 4 THEN ?p_23 WHEN 5 THEN ?p_24 WHEN 6 THEN ?p_25 WHEN 7 THEN ?p_26 WHEN 8 THEN ?p_27 WHEN 9 THEN ?p_28 WHEN 10 THEN ?p_29 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = CASE `Id` WHEN 1 THEN ?p_0 WHEN 2 THEN ?p_1 WHEN 3 THEN ?p_2 WHEN 4 THEN ?p_3 WHEN 5 THEN ?p_4 WHEN 6 THEN ?p_5 WHEN 7 THEN ?p_6 WHEN 8 THEN ?p_7 WHEN 9 THEN ?p_8 WHEN 10 THEN ?p_9 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = CASE `Id` WHEN 1 THEN ?p_0 WHEN 2 THEN ?p_1 WHEN 3 THEN ?p_2 WHEN 4 THEN ?p_3 WHEN 5 THEN ?p_4 WHEN 6 THEN ?p_5 WHEN 7 THEN ?p_6 WHEN 8 THEN ?p_7 WHEN 9 THEN ?p_8 WHEN 10 THEN ?p_9 END WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020,1,1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `CreateTime` = ?p_0 WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `CreateTime` = ?p_0 WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); - Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql); - var id = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); - Assert.True(id > 0); - Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); + sql = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); + Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES(?type_0, ?time_0)", sql); + var id = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); + Assert.True(id > 0); + Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); - sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0, `time` = ?p_1 WHERE (`id` = 0)", sql); - g.mysql.Update().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows(); - Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); + sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0, `time` = ?p_1 WHERE (`id` = 0)", sql); + g.mysql.Update().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows(); + Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); - sql = g.mysql.Insert().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); - Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); - id = g.mysql.Insert().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); - Assert.True(id > 0); - Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); + sql = g.mysql.Insert().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); + Assert.Equal("INSERT INTO `TestEnumUpdateTb`(`type`, `time`) VALUES('sum211', '0001-01-01 00:00:00.000')", sql); + id = g.mysql.Insert().NoneParameter().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); + Assert.True(id > 0); + Assert.Equal(TestEnumUpdateTbType.sum211, g.mysql.Select().Where(a => a.id == id).First()?.type); - sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211', `time` = '0001-01-01 00:00:00.000' WHERE (`id` = 0)", sql); - g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows(); - Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); - } - [Fact] - public void IgnoreColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211', `time` = '0001-01-01 00:00:00.000' WHERE (`id` = 0)", sql); + g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { id = (int)id, type = TestEnumUpdateTbType.biggit }).ExecuteAffrows(); + Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); + } + [Fact] + public void IgnoreColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql); - sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = 0)", sql); + sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = 0)", sql); - sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); - } - [Fact] - public void UpdateColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).IgnoreColumns(a => a.time).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); + } + [Fact] + public void UpdateColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql); - sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = 0)", sql); + sql = g.mysql.Update().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = 0)", sql); - sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); - } - [Fact] - public void Set() { - var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().SetSource(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).UpdateColumns(a => a.type).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); + } + [Fact] + public void Set() + { + var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0 WHERE (`Id` = 1)", sql); - sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0, `CreateTime` = ?p_1 WHERE (`Id` = 1)", sql); + sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Title` = ?p_0, `CreateTime` = ?p_1 WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql); - int incrv = 10; - sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql); + int incrv = 10; + sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = ifnull(`Clicks`, 0) * 10 / 1 WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Id` = (`Id` - 10) WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Clicks` = `Clicks` * 10 / 1 WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Clicks` = `Clicks` * 10 / 1 WHERE (`Id` = 1)", sql); - sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET `Id` = 10 WHERE (`Id` = 1)", sql); + sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET `Id` = 10 WHERE (`Id` = 1)", sql); - var id = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); - Assert.True(id > 0); - sql = g.mysql.Update().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", ""); - Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = {id})", sql); - g.mysql.Update().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ExecuteAffrows(); - Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); + var id = g.mysql.Insert().AppendData(new TestEnumUpdateTb { type = TestEnumUpdateTbType.sum211 }).ExecuteIdentity(); + Assert.True(id > 0); + sql = g.mysql.Update().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ToSql().Replace("\r\n", ""); + Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = ?p_0 WHERE (`id` = {id})", sql); + g.mysql.Update().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.biggit).ExecuteAffrows(); + Assert.Equal(TestEnumUpdateTbType.biggit, g.mysql.Select().Where(a => a.id == id).First()?.type); - sql = g.mysql.Update().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ToSql().Replace("\r\n", ""); - Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = 'str1' WHERE (`id` = {id})", sql); - g.mysql.Update().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ExecuteAffrows(); - Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select().Where(a => a.id == id).First()?.type); - } - [Fact] - public void SetRaw() { - var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + ?incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET clicks = clicks + ?incrClick WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ToSql().Replace("\r\n", ""); + Assert.Equal($"UPDATE `TestEnumUpdateTb` SET `type` = 'str1' WHERE (`id` = {id})", sql); + g.mysql.Update().NoneParameter().Where(a => a.id == id).Set(a => a.type, TestEnumUpdateTbType.str1).ExecuteAffrows(); + Assert.Equal(TestEnumUpdateTbType.str1, g.mysql.Select().Where(a => a.id == id).First()?.type); + } + [Fact] + public void SetRaw() + { + var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + ?incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET clicks = clicks + ?incrClick WHERE (`Id` = 1)", sql); - sql = g.mysql.Update().NoneParameter().Where(a => a.id == 0).SetRaw("`type` = {0}".FormatMySql(TestEnumUpdateTbType.sum211)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); - } - [Fact] - public void Where() { - var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); + sql = g.mysql.Update().NoneParameter().Where(a => a.id == 0).SetRaw("`type` = {0}".FormatMySql(TestEnumUpdateTbType.sum211)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0)", sql); + } + [Fact] + public void Where() + { + var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); - sql = update.Where("id = ?id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = ?id)", sql); + sql = update.Where("id = ?id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (id = ?id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `tb_topic` SET title='newtitle' WHERE (`Id` IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = g.mysql.Update().NoneParameter().Where(a => a.id == 0 && a.type == TestEnumUpdateTbType.str1) - .Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql); - } - [Fact] - public void WhereExists() { + sql = g.mysql.Update().NoneParameter().Where(a => a.id == 0 && a.type == TestEnumUpdateTbType.str1) + .Set(a => a.type, TestEnumUpdateTbType.sum211).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE `TestEnumUpdateTb` SET `type` = 'sum211' WHERE (`id` = 0 AND `type` = 'str1')", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - } - [Fact] - public void ExecuteUpdated() { + } + [Fact] + public void ExecuteUpdated() + { - } + } - [Fact] - public void AsTable() { - Assert.Null(g.mysql.Update().ToSql()); - Assert.Equal("UPDATE `tb_topicAsTable` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - } - } + [Fact] + public void AsTable() + { + Assert.Null(g.mysql.Update().ToSql()); + Assert.Equal("UPDATE `tb_topicAsTable` SET title='test' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1 OR `Id` = 2)", g.mysql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE `tb_topicAsTable` SET title='test1' \r\nWHERE (`Id` = 1)", g.mysql.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MapType/BoolNullableTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MapType/BoolNullableTest.cs index bcff25e2..b4f476c2 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MapType/BoolNullableTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MapType/BoolNullableTest.cs @@ -2,1561 +2,1595 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.MySqlMapType { - public class BoolNullableTest { - class BoolNullableMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool))] - public bool? tobool { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool? tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool? tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool? toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool? toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool? toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool? tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool? tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool? tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool? tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool? tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool? toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool? toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool? touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool? touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool? toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool? toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool? tostring { get; set; } = true; - } - [Fact] - public void Bool() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item = new BoolNullableMap { tobool = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item = new BoolNullableMap { tobool = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update all - item.tobool = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item.tobool = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item.tobool = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item = new BoolNullableMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item = new BoolNullableMap { tosbyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item.tosbyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item.tosbytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item = new BoolNullableMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item = new BoolNullableMap { toshort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item.toshort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item.toshortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item = new BoolNullableMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item = new BoolNullableMap { toint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item.toint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item = new BoolNullableMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item = new BoolNullableMap { tointnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item.tointnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item = new BoolNullableMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item = new BoolNullableMap { tolong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item.tolong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item.tolongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item = new BoolNullableMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item = new BoolNullableMap { tobyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item.tobyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item.tobytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item = new BoolNullableMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item = new BoolNullableMap { toushort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item.toushort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item.toushortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item = new BoolNullableMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item = new BoolNullableMap { touint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item.touint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item = new BoolNullableMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item = new BoolNullableMap { touintnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item.touintnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item = new BoolNullableMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item = new BoolNullableMap { toulong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item.toulong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item.toulongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.mysql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item = new BoolNullableMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item = new BoolNullableMap { tostring = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item.tostring = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.MySqlMapType +{ + public class BoolNullableTest + { + class BoolNullableMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool))] + public bool? tobool { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool? tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool? tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool? toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool? toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool? toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool? tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool? tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool? tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool? tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool? tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool? toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool? toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool? touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool? touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool? toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool? toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool? tostring { get; set; } = true; + } + [Fact] + public void Bool() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item = new BoolNullableMap { tobool = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item = new BoolNullableMap { tobool = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update all + item.tobool = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item.tobool = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item.tobool = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item = new BoolNullableMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item = new BoolNullableMap { tosbyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item.tosbyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item.tosbytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item = new BoolNullableMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item = new BoolNullableMap { toshort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item.toshort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item.toshortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item = new BoolNullableMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item = new BoolNullableMap { toint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item.toint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item = new BoolNullableMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item = new BoolNullableMap { tointnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item.tointnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item = new BoolNullableMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item = new BoolNullableMap { tolong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item.tolong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item.tolongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item = new BoolNullableMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item = new BoolNullableMap { tobyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item.tobyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item.tobytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item = new BoolNullableMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item = new BoolNullableMap { toushort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item.toushort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item.toushortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item = new BoolNullableMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item = new BoolNullableMap { touint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item.touint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item = new BoolNullableMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item = new BoolNullableMap { touintnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item.touintnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item = new BoolNullableMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item = new BoolNullableMap { toulong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item.toulong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item.toulongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.mysql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item = new BoolNullableMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item = new BoolNullableMap { tostring = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item.tostring = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MapType/BoolTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MapType/BoolTest.cs index 44cdd2cb..b65dd1be 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MapType/BoolTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MapType/BoolTest.cs @@ -2,1095 +2,1129 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.MySqlMapType { - public class BoolTest { - - class BoolMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool?))] - public bool toboolnullable { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool tostring { get; set; } = true; - } - - [Fact] - public void BoolNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item = new BoolMap { toboolnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update all - item.toboolnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item.toboolnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toboolnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toboolnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item = new BoolMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item = new BoolMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item = new BoolMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item = new BoolMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item = new BoolMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item = new BoolMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item = new BoolMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item = new BoolMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item = new BoolMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item = new BoolMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item = new BoolMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item = new BoolMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item = new BoolMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item = new BoolMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item = new BoolMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item = new BoolMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.mysql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item = new BoolMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.MySqlMapType +{ + public class BoolTest + { + + class BoolMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool?))] + public bool toboolnullable { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool tostring { get; set; } = true; + } + + [Fact] + public void BoolNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item = new BoolMap { toboolnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update all + item.toboolnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item.toboolnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toboolnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toboolnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item = new BoolMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item = new BoolMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item = new BoolMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item = new BoolMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item = new BoolMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item = new BoolMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item = new BoolMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item = new BoolMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item = new BoolMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item = new BoolMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item = new BoolMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item = new BoolMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item = new BoolMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item = new BoolMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item = new BoolMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item = new BoolMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.mysql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item = new BoolMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MapType/EnumTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MapType/EnumTest.cs index 58ac7908..cf34a3e4 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MapType/EnumTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MapType/EnumTest.cs @@ -3,252 +3,259 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.MySqlMapType { - public class EnumTest { - class EnumTestMap { - public Guid id { get; set; } +namespace FreeSql.Tests.MySqlMapType +{ + public class EnumTest + { + class EnumTestMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(int))] - public ToStringMapEnum enum_to_int { get; set; } - [Column(MapType = typeof(int?))] - public ToStringMapEnum? enumnullable_to_int { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void EnumToString() { - //insert - var orm = g.mysql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(int))] + public ToStringMapEnum enum_to_int { get; set; } + [Column(MapType = typeof(int?))] + public ToStringMapEnum? enumnullable_to_int { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void EnumToString() + { + //insert + var orm = g.mysql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToString() { - //insert - var orm = g.mysql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToString() + { + //insert + var orm = g.mysql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void EnumToInt() { - //insert - var orm = g.mysql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + [Fact] + public void EnumToInt() + { + //insert + var orm = g.mysql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //update all - item.enum_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update all + item.enum_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - item.enum_to_int = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + item.enum_to_int = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToInt() { - //insert - var orm = g.mysql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToInt() + { + //insert + var orm = g.mysql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); + item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); - //update all - item.enumnullable_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); + //update all + item.enumnullable_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); - item.enumnullable_to_int = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + item.enumnullable_to_int = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MapType/ToStringTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MapType/ToStringTest.cs index b18962e7..fb4db4ca 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MapType/ToStringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MapType/ToStringTest.cs @@ -3,555 +3,568 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.MySqlMapType { - public class ToStringTest { - class ToStringMap { - public Guid id { get; set; } +namespace FreeSql.Tests.MySqlMapType +{ + public class ToStringTest + { + class ToStringMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan timespan_to_string { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan? timespannullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan timespan_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan? timespannullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime datetime_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime? datetimenullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime datetime_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime? datetimenullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid guid_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid? guidnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid guid_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid? guidnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger biginteger_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger? bigintegernullable_to_string { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void Enum1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(string))] + public BigInteger biginteger_to_string { get; set; } + [Column(MapType = typeof(string))] + public BigInteger? bigintegernullable_to_string { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void Enum1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigInteger1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(0, find.biginteger_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigInteger1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(0, find.biginteger_to_string); - item = new ToStringMap { biginteger_to_string = 100 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(100, find.biginteger_to_string); + item = new ToStringMap { biginteger_to_string = 100 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(100, find.biginteger_to_string); - //update all - item.biginteger_to_string = 200; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(200, find.biginteger_to_string); + //update all + item.biginteger_to_string = 200; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(200, find.biginteger_to_string); - item.biginteger_to_string = 205; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(205, find.biginteger_to_string); + item.biginteger_to_string = 205; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(205, find.biginteger_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(522, find.biginteger_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(522, find.biginteger_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(10005, find.biginteger_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(10005, find.biginteger_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigIntegerNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigIntegerNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - item = new ToStringMap { bigintegernullable_to_string = 101 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(101, find.bigintegernullable_to_string); + item = new ToStringMap { bigintegernullable_to_string = 101 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(101, find.bigintegernullable_to_string); - //update all - item.bigintegernullable_to_string = 2004; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(2004, find.bigintegernullable_to_string); + //update all + item.bigintegernullable_to_string = 2004; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(2004, find.bigintegernullable_to_string); - item.bigintegernullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + item.bigintegernullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(998, find.bigintegernullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(998, find.bigintegernullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.bigintegernullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.bigintegernullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpan1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.Zero, find.timespan_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpan1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.Zero, find.timespan_to_string); - item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); + item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); - //update all - item.timespan_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); + //update all + item.timespan_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpanNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpanNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); + item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); - //update all - item.timespannullable_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); + //update all + item.timespannullable_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); - item.timespannullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + item.timespannullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.timespannullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.timespannullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTime1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.MinValue, find.datetime_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTime1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.MinValue, find.datetime_to_string); - item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); + item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); - //update all - item.datetime_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); + //update all + item.datetime_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTimeNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTimeNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); + item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); - //update all - item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); + //update all + item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); - item.datetimenullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + item.datetimenullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.datetimenullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.datetimenullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void Guid1() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(Guid.Empty, find.guid_to_string); + [Fact] + public void Guid1() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(Guid.Empty, find.guid_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guid_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guid_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update all - newid = Guid.NewGuid(); - item.guid_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + //update all + newid = Guid.NewGuid(); + item.guid_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guid_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guid_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void GuidNullable() { - //insert - var orm = g.mysql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void GuidNullable() + { + //insert + var orm = g.mysql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guidnullable_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guidnullable_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - //update all - newid = Guid.NewGuid(); - item.guidnullable_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + //update all + newid = Guid.NewGuid(); + item.guidnullable_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - item.guidnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + item.guidnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guidnullable_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guidnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.guidnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.guidnullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlAdo/MySqlAdoTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlAdo/MySqlAdoTest.cs index b6053ea3..ab37eda6 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlAdo/MySqlAdoTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlAdo/MySqlAdoTest.cs @@ -2,53 +2,64 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.MySql { - public class MySqlAdoTest { - [Fact] - public void Pool() { - var t1 = g.mysql.Ado.MasterPool.StatisticsFullily; - } +namespace FreeSql.Tests.MySql +{ + public class MySqlAdoTest + { + [Fact] + public void Pool() + { + var t1 = g.mysql.Ado.MasterPool.StatisticsFullily; + } - [Fact] - public void SlavePools() { - var t2 = g.mysql.Ado.SlavePools.Count; - } + [Fact] + public void SlavePools() + { + var t2 = g.mysql.Ado.SlavePools.Count; + } - [Fact] - public void ExecuteReader() { - - } - [Fact] - public void ExecuteArray() { - - } - [Fact] - public void ExecuteNonQuery() { - - } - [Fact] - public void ExecuteScalar() { - - } + [Fact] + public void ExecuteReader() + { - [Fact] - public void Query() { - var t3 = g.mysql.Ado.Query("select * from song"); + } + [Fact] + public void ExecuteArray() + { - var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song"); + } + [Fact] + public void ExecuteNonQuery() + { - var t5 = g.mysql.Ado.Query("select * from song"); - } + } + [Fact] + public void ExecuteScalar() + { - [Fact] - public void QueryMultipline() { - var t3 = g.mysql.Ado.Query("select * from song; select * from song; select * from song"); - } + } - class xxx { - public int Id { get; set; } - public string Path { get; set; } - public string Title2 { get; set; } - } - } + [Fact] + public void Query() + { + var t3 = g.mysql.Ado.Query("select * from song"); + + var t4 = g.mysql.Ado.Query<(int, string, string)>("select * from song"); + + var t5 = g.mysql.Ado.Query("select * from song"); + } + + [Fact] + public void QueryMultipline() + { + var t3 = g.mysql.Ado.Query("select * from song; select * from song; select * from song"); + } + + class xxx + { + public int Id { get; set; } + public string Path { get; set; } + public string Title2 { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlCodeFirstTest.cs index 11b7c086..123f782e 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlCodeFirstTest.cs @@ -6,80 +6,91 @@ using System.Linq; using System.Text; using Xunit; -namespace FreeSql.Tests.MySql { - public class MySqlCodeFirstTest { +namespace FreeSql.Tests.MySql +{ + public class MySqlCodeFirstTest + { - [Fact] - public void ı_ֶ() { - var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<ı2>(); - g.mysql.CodeFirst.SyncStructure<ı2>(); + [Fact] + public void ı_ֶ() + { + var sql = g.mysql.CodeFirst.GetComparisonDDLStatements<ı2>(); + g.mysql.CodeFirst.SyncStructure<ı2>(); - var item = new ı2 { - = "Ա", - ʱ = DateTime.Now - }; - Assert.Equal(1, g.mysql.Insert<ı2>().AppendData(item).ExecuteAffrows()); - Assert.NotEqual(Guid.Empty, item.); - var item2 = g.mysql.Select<ı2>().Where(a => a. == item.).First(); - Assert.NotNull(item2); - Assert.Equal(item., item2.); - Assert.Equal(item., item2.); - } - class ı2 { - [Column(IsPrimary = true)] - public Guid { get; set; } + var item = new ı2 + { + = "Ա", + ʱ = DateTime.Now + }; + Assert.Equal(1, g.mysql.Insert<ı2>().AppendData(item).ExecuteAffrows()); + Assert.NotEqual(Guid.Empty, item.); + var item2 = g.mysql.Select<ı2>().Where(a => a. == item.).First(); + Assert.NotNull(item2); + Assert.Equal(item., item2.); + Assert.Equal(item., item2.); + } + class ı2 + { + [Column(IsPrimary = true)] + public Guid { get; set; } - public string { get; set; } + public string { get; set; } - public DateTime ʱ { get; set; } - } + public DateTime ʱ { get; set; } + } - [Fact] - public void AddUniques() { - var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); - g.mysql.CodeFirst.SyncStructure(); - } - [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] - class AddUniquesInfo { - public Guid id { get; set; } - [Column(Unique = "uk_phone")] - public string phone { get; set; } + [Fact] + public void AddUniques() + { + var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); + g.mysql.CodeFirst.SyncStructure(); + } + [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] + class AddUniquesInfo + { + public Guid id { get; set; } + [Column(Unique = "uk_phone")] + public string phone { get; set; } - [Column(Unique = "uk_group_index, uk_group_index22")] - public string group { get; set; } - [Column(Unique = "uk_group_index")] - public int index { get; set; } - [Column(Unique = "uk_group_index22")] - public string index22 { get; set; } - } + [Column(Unique = "uk_group_index, uk_group_index22")] + public string group { get; set; } + [Column(Unique = "uk_group_index")] + public int index { get; set; } + [Column(Unique = "uk_group_index22")] + public string index22 { get; set; } + } - [Fact] - public void AddField() { - var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); + [Fact] + public void AddField() + { + var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); - var id = g.mysql.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); - } + var id = g.mysql.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); + } - [Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")] - public class TopicAddField { - [Column(IsIdentity = true)] - public int? Id { get; set; } + [Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")] + public class TopicAddField + { + [Column(IsIdentity = true)] + public int? Id { get; set; } - public string name { get; set; } + public string name { get; set; } - [Column(DbType = "varchar(200) not null", OldName = "title")] - public string title222 { get; set; } = "10"; + [Column(DbType = "varchar(200) not null", OldName = "title")] + public string title222 { get; set; } = "10"; - [Column(IsIgnore = true)] - public DateTime ct { get; set; } = DateTime.Now; - } + [Column(IsIgnore = true)] + public DateTime ct { get; set; } = DateTime.Now; + } - [Fact] - public void GetComparisonDDLStatements() { + [Fact] + public void GetComparisonDDLStatements() + { - var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); - if (string.IsNullOrEmpty(sql) == false) { - Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` ( + var sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); + if (string.IsNullOrEmpty(sql) == false) + { + Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` ( `Id` INT(11) NOT NULL AUTO_INCREMENT, `testFieldBool` BIT(1) NOT NULL, `testFieldSByte` TINYINT(3) NOT NULL, @@ -126,352 +137,363 @@ namespace FreeSql.Tests.MySql { PRIMARY KEY (`Id`) ) Engine=InnoDB; ", sql); - } - - sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); - } - - IInsert insert => g.mysql.Insert(); - ISelect select => g.mysql.Select(); - - [Fact] - public void CurdAllField() { - var item = new TableAllType { }; - item.Id = (int)insert.AppendData(item).ExecuteIdentity(); - - var newitem = select.Where(a => a.Id == item.Id).ToOne(); - - var item2 = new TableAllType { - testFieldBool = true, - testFieldBoolNullable = true, - testFieldByte = 255, - testFieldByteNullable = 127, - testFieldBytes = Encoding.UTF8.GetBytes("й"), - testFieldDateTime = DateTime.Now, - testFieldDateTimeNullable = DateTime.Now.AddHours(-1), - testFieldDecimal = 99.99M, - testFieldDecimalNullable = 99.98M, - testFieldDouble = 999.99, - testFieldDoubleNullable = 999.98, - testFieldEnum1 = TableAllTypeEnumType1.e5, - testFieldEnum1Nullable = TableAllTypeEnumType1.e3, - testFieldEnum2 = TableAllTypeEnumType2.f2, - testFieldEnum2Nullable = TableAllTypeEnumType2.f3, - testFieldFloat = 19.99F, - testFieldFloatNullable = 19.98F, - testFieldGuid = Guid.NewGuid(), - testFieldGuidNullable = Guid.NewGuid(), - testFieldInt = int.MaxValue, - testFieldIntNullable = int.MinValue, - testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }), - testFieldLong = long.MaxValue, - testFieldMultiLineString = new MygisMultiLineString(new[] { - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }, - new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }), - testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }), - testFieldMultiPolygon = new MygisMultiPolygon(new[] { - new MygisPolygon(new[] { - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }), - new MygisPolygon(new[] { - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }), - testFieldPoint = new MygisPoint(99, 99), - testFieldPolygon = new MygisPolygon(new[] { - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, - new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }), - testFieldSByte = 100, - testFieldSByteNullable = 99, - testFieldShort = short.MaxValue, - testFieldShortNullable = short.MinValue, - testFieldString = "йstring", - testFieldTimeSpan = TimeSpan.FromSeconds(999), - testFieldTimeSpanNullable = TimeSpan.FromSeconds(60), - testFieldUInt = uint.MaxValue, - testFieldUIntNullable = uint.MinValue, - testFieldULong = ulong.MaxValue, - testFieldULongNullable = ulong.MinValue, - testFieldUShort = ushort.MaxValue, - testFieldUShortNullable = ushort.MinValue, - testFielLongNullable = long.MinValue - }; - item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); - var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); + } + + sql = g.mysql.CodeFirst.GetComparisonDDLStatements(); + } + + IInsert insert => g.mysql.Insert(); + ISelect select => g.mysql.Select(); + + [Fact] + public void CurdAllField() + { + var item = new TableAllType { }; + item.Id = (int)insert.AppendData(item).ExecuteIdentity(); + + var newitem = select.Where(a => a.Id == item.Id).ToOne(); + + var item2 = new TableAllType + { + testFieldBool = true, + testFieldBoolNullable = true, + testFieldByte = 255, + testFieldByteNullable = 127, + testFieldBytes = Encoding.UTF8.GetBytes("й"), + testFieldDateTime = DateTime.Now, + testFieldDateTimeNullable = DateTime.Now.AddHours(-1), + testFieldDecimal = 99.99M, + testFieldDecimalNullable = 99.98M, + testFieldDouble = 999.99, + testFieldDoubleNullable = 999.98, + testFieldEnum1 = TableAllTypeEnumType1.e5, + testFieldEnum1Nullable = TableAllTypeEnumType1.e3, + testFieldEnum2 = TableAllTypeEnumType2.f2, + testFieldEnum2Nullable = TableAllTypeEnumType2.f3, + testFieldFloat = 19.99F, + testFieldFloatNullable = 19.98F, + testFieldGuid = Guid.NewGuid(), + testFieldGuidNullable = Guid.NewGuid(), + testFieldInt = int.MaxValue, + testFieldIntNullable = int.MinValue, + testFieldLineString = new MygisLineString(new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }), + testFieldLong = long.MaxValue, + testFieldMultiLineString = new MygisMultiLineString(new[] { + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10) }, + new[] { new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 100) } }), + testFieldMultiPoint = new MygisMultiPoint(new[] { new MygisCoordinate2D(11, 11), new MygisCoordinate2D(51, 11) }), + testFieldMultiPolygon = new MygisMultiPolygon(new[] { + new MygisPolygon(new[] { + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }), + new MygisPolygon(new[] { + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }) }), + testFieldPoint = new MygisPoint(99, 99), + testFieldPolygon = new MygisPolygon(new[] { + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) }, + new[] { new MygisCoordinate2D(10, 10), new MygisCoordinate2D(50, 10), new MygisCoordinate2D(10, 50), new MygisCoordinate2D(10, 10) } }), + testFieldSByte = 100, + testFieldSByteNullable = 99, + testFieldShort = short.MaxValue, + testFieldShortNullable = short.MinValue, + testFieldString = "йstring", + testFieldTimeSpan = TimeSpan.FromSeconds(999), + testFieldTimeSpanNullable = TimeSpan.FromSeconds(60), + testFieldUInt = uint.MaxValue, + testFieldUIntNullable = uint.MinValue, + testFieldULong = ulong.MaxValue, + testFieldULongNullable = ulong.MinValue, + testFieldUShort = ushort.MaxValue, + testFieldUShortNullable = ushort.MinValue, + testFielLongNullable = long.MinValue + }; + item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); + var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); - var items = select.ToList(); - } + var items = select.ToList(); + } - [JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")] - public partial class Tb_alltype { + [JsonObject(MemberSerialization.OptIn), Table(Name = "tb_alltype")] + public partial class Tb_alltype + { - [JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)] - public int Id { get; set; } + [JsonProperty, Column(Name = "Id", DbType = "int(11)", IsPrimary = true, IsIdentity = true)] + public int Id { get; set; } - [JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")] - public bool TestFieldBool { get; set; } + [JsonProperty, Column(Name = "testFieldBool", DbType = "bit(1)")] + public bool TestFieldBool { get; set; } - [JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)] - public bool? TestFieldBoolNullable { get; set; } + [JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit(1)", IsNullable = true)] + public bool? TestFieldBoolNullable { get; set; } - [JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")] - public byte TestFieldByte { get; set; } + [JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint(3) unsigned")] + public byte TestFieldByte { get; set; } - [JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)] - public byte? TestFieldByteNullable { get; set; } + [JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint(3) unsigned", IsNullable = true)] + public byte? TestFieldByteNullable { get; set; } - [JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)] - public byte[] TestFieldBytes { get; set; } + [JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)] + public byte[] TestFieldBytes { get; set; } - [JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")] - public DateTime TestFieldDateTime { get; set; } + [JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")] + public DateTime TestFieldDateTime { get; set; } - [JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)] - public DateTime? TestFieldDateTimeNullable { get; set; } + [JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)] + public DateTime? TestFieldDateTimeNullable { get; set; } - [JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")] - public decimal TestFieldDecimal { get; set; } + [JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")] + public decimal TestFieldDecimal { get; set; } - [JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)] - public decimal? TestFieldDecimalNullable { get; set; } + [JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)] + public decimal? TestFieldDecimalNullable { get; set; } - [JsonProperty, Column(Name = "testFieldDouble", DbType = "double")] - public double TestFieldDouble { get; set; } + [JsonProperty, Column(Name = "testFieldDouble", DbType = "double")] + public double TestFieldDouble { get; set; } - [JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)] - public double? TestFieldDoubleNullable { get; set; } + [JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "double", IsNullable = true)] + public double? TestFieldDoubleNullable { get; set; } - [JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")] - public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; } + [JsonProperty, Column(Name = "testFieldEnum1", DbType = "enum('E1','E2','E3','E5')")] + public Tb_alltypeTESTFIELDENUM1 TestFieldEnum1 { get; set; } - [JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)] - public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; } + [JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "enum('E1','E2','E3','E5')", IsNullable = true)] + public Tb_alltypeTESTFIELDENUM1NULLABLE? TestFieldEnum1Nullable { get; set; } - [JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")] - public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; } + [JsonProperty, Column(Name = "testFieldEnum2", DbType = "set('F1','F2','F3')")] + public Tb_alltypeTESTFIELDENUM2 TestFieldEnum2 { get; set; } - [JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)] - public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; } + [JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "set('F1','F2','F3')", IsNullable = true)] + public Tb_alltypeTESTFIELDENUM2NULLABLE? TestFieldEnum2Nullable { get; set; } - [JsonProperty, Column(Name = "testFieldFloat", DbType = "float")] - public float TestFieldFloat { get; set; } + [JsonProperty, Column(Name = "testFieldFloat", DbType = "float")] + public float TestFieldFloat { get; set; } - [JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)] - public float? TestFieldFloatNullable { get; set; } + [JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "float", IsNullable = true)] + public float? TestFieldFloatNullable { get; set; } - [JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")] - public Guid TestFieldGuid { get; set; } + [JsonProperty, Column(Name = "testFieldGuid", DbType = "char(36)")] + public Guid TestFieldGuid { get; set; } - [JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)] - public Guid? TestFieldGuidNullable { get; set; } + [JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "char(36)", IsNullable = true)] + public Guid? TestFieldGuidNullable { get; set; } - [JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")] - public int TestFieldInt { get; set; } + [JsonProperty, Column(Name = "testFieldInt", DbType = "int(11)")] + public int TestFieldInt { get; set; } - [JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)] - public int? TestFieldIntNullable { get; set; } + [JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int(11)", IsNullable = true)] + public int? TestFieldIntNullable { get; set; } - [JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)] - public MygisGeometry TestFieldLineString { get; set; } + [JsonProperty, Column(Name = "testFieldLineString", DbType = "linestring", IsNullable = true)] + public MygisGeometry TestFieldLineString { get; set; } - [JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")] - public long TestFieldLong { get; set; } + [JsonProperty, Column(Name = "testFieldLong", DbType = "bigint(20)")] + public long TestFieldLong { get; set; } - [JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)] - public MygisGeometry TestFieldMultiLineString { get; set; } + [JsonProperty, Column(Name = "testFieldMultiLineString", DbType = "multilinestring", IsNullable = true)] + public MygisGeometry TestFieldMultiLineString { get; set; } - [JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)] - public MygisGeometry TestFieldMultiPoint { get; set; } + [JsonProperty, Column(Name = "testFieldMultiPoint", DbType = "multipoint", IsNullable = true)] + public MygisGeometry TestFieldMultiPoint { get; set; } - [JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)] - public MygisGeometry TestFieldMultiPolygon { get; set; } + [JsonProperty, Column(Name = "testFieldMultiPolygon", DbType = "multipolygon", IsNullable = true)] + public MygisGeometry TestFieldMultiPolygon { get; set; } - [JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)] - public MygisGeometry TestFieldPoint { get; set; } + [JsonProperty, Column(Name = "testFieldPoint", DbType = "point", IsNullable = true)] + public MygisGeometry TestFieldPoint { get; set; } - [JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)] - public MygisGeometry TestFieldPolygon { get; set; } + [JsonProperty, Column(Name = "testFieldPolygon", DbType = "polygon", IsNullable = true)] + public MygisGeometry TestFieldPolygon { get; set; } - [JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")] - public sbyte TestFieldSByte { get; set; } + [JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint(3)")] + public sbyte TestFieldSByte { get; set; } - [JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)] - public sbyte? TestFieldSByteNullable { get; set; } + [JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint(3)", IsNullable = true)] + public sbyte? TestFieldSByteNullable { get; set; } - [JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")] - public short TestFieldShort { get; set; } + [JsonProperty, Column(Name = "testFieldShort", DbType = "smallint(6)")] + public short TestFieldShort { get; set; } - [JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)] - public short? TestFieldShortNullable { get; set; } + [JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint(6)", IsNullable = true)] + public short? TestFieldShortNullable { get; set; } - [JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)] - public string TestFieldString { get; set; } + [JsonProperty, Column(Name = "testFieldString", DbType = "varchar(255)", IsNullable = true)] + public string TestFieldString { get; set; } - [JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")] - public TimeSpan TestFieldTimeSpan { get; set; } + [JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")] + public TimeSpan TestFieldTimeSpan { get; set; } - [JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)] - public TimeSpan? TestFieldTimeSpanNullable { get; set; } + [JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)] + public TimeSpan? TestFieldTimeSpanNullable { get; set; } - [JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")] - public uint TestFieldUInt { get; set; } + [JsonProperty, Column(Name = "testFieldUInt", DbType = "int(10) unsigned")] + public uint TestFieldUInt { get; set; } - [JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)] - public uint? TestFieldUIntNullable { get; set; } + [JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int(10) unsigned", IsNullable = true)] + public uint? TestFieldUIntNullable { get; set; } - [JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")] - public ulong TestFieldULong { get; set; } + [JsonProperty, Column(Name = "testFieldULong", DbType = "bigint(20) unsigned")] + public ulong TestFieldULong { get; set; } - [JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)] - public ulong? TestFieldULongNullable { get; set; } + [JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint(20) unsigned", IsNullable = true)] + public ulong? TestFieldULongNullable { get; set; } - [JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")] - public ushort TestFieldUShort { get; set; } + [JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint(5) unsigned")] + public ushort TestFieldUShort { get; set; } - [JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)] - public ushort? TestFieldUShortNullable { get; set; } + [JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint(5) unsigned", IsNullable = true)] + public ushort? TestFieldUShortNullable { get; set; } - [JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)] - public long? TestFielLongNullable { get; set; } + [JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint(20)", IsNullable = true)] + public long? TestFielLongNullable { get; set; } - internal static IFreeSql mysql => null; - public static FreeSql.ISelect Select => mysql.Select(); + internal static IFreeSql mysql => null; + public static FreeSql.ISelect Select => mysql.Select(); - public static long Delete(int Id) { - var affrows = mysql.Delete().Where(a => a.Id == Id).ExecuteAffrows(); - return affrows; - } + public static long Delete(int Id) + { + var affrows = mysql.Delete().Where(a => a.Id == Id).ExecuteAffrows(); + return affrows; + } - /// - /// ӣֵ UpdateӰΪ 0 Insert - /// - public void Save() { - if (this.Id != default(int)) { - var affrows = mysql.Update().Where(a => a.Id == Id).ExecuteAffrows(); - if (affrows > 0) return; - } - this.Id = (int)mysql.Insert().AppendData(this).ExecuteIdentity(); - } + /// + /// ӣֵ UpdateӰΪ 0 Insert + /// + public void Save() + { + if (this.Id != default(int)) + { + var affrows = mysql.Update().Where(a => a.Id == Id).ExecuteAffrows(); + if (affrows > 0) return; + } + this.Id = (int)mysql.Insert().AppendData(this).ExecuteIdentity(); + } - } + } - public enum Tb_alltypeTESTFIELDENUM1 { - E1 = 1, E2, E3, E5 - } - public enum Tb_alltypeTESTFIELDENUM1NULLABLE { - E1 = 1, E2, E3, E5 - } - [Flags] - public enum Tb_alltypeTESTFIELDENUM2 : long { - F1 = 1, F2 = 2, F3 = 4 - } - [Flags] - public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long { - F1 = 1, F2 = 2, F3 = 4 - } + public enum Tb_alltypeTESTFIELDENUM1 + { + E1 = 1, E2, E3, E5 + } + public enum Tb_alltypeTESTFIELDENUM1NULLABLE + { + E1 = 1, E2, E3, E5 + } + [Flags] + public enum Tb_alltypeTESTFIELDENUM2 : long + { + F1 = 1, F2 = 2, F3 = 4 + } + [Flags] + public enum Tb_alltypeTESTFIELDENUM2NULLABLE : long + { + F1 = 1, F2 = 2, F3 = 4 + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - - public bool testFieldBool { get; set; } - public sbyte testFieldSByte { get; set; } - public short testFieldShort { get; set; } - public int testFieldInt { get; set; } - public long testFieldLong { get; set; } - public byte testFieldByte { get; set; } - public ushort testFieldUShort { get; set; } - public uint testFieldUInt { get; set; } - public ulong testFieldULong { get; set; } - public double testFieldDouble { get; set; } - public float testFieldFloat { get; set; } - public decimal testFieldDecimal { get; set; } - public TimeSpan testFieldTimeSpan { get; set; } - public DateTime testFieldDateTime { get; set; } - public byte[] testFieldBytes { get; set; } - public string testFieldString { get; set; } - public Guid testFieldGuid { get; set; } - - public bool? testFieldBoolNullable { get; set; } - public sbyte? testFieldSByteNullable { get; set; } - public short? testFieldShortNullable { get; set; } - public int? testFieldIntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? testFieldByteNullable { get; set; } - public ushort? testFieldUShortNullable { get; set; } - public uint? testFieldUIntNullable { get; set; } - public ulong? testFieldULongNullable { get; set; } - public double? testFieldDoubleNullable { get; set; } - public float? testFieldFloatNullable { get; set; } - public decimal? testFieldDecimalNullable { get; set; } - public TimeSpan? testFieldTimeSpanNullable { get; set; } - public DateTime? testFieldDateTimeNullable { get; set; } - public Guid? testFieldGuidNullable { get; set; } - - public MygisPoint testFieldPoint { get; set; } - public MygisLineString testFieldLineString { get; set; } - public MygisPolygon testFieldPolygon { get; set; } - public MygisMultiPoint testFieldMultiPoint { get; set; } - public MygisMultiLineString testFieldMultiLineString { get; set; } - public MygisMultiPolygon testFieldMultiPolygon { get; set; } - - public TableAllTypeEnumType1 testFieldEnum1 { get; set; } - public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } - public TableAllTypeEnumType2 testFieldEnum2 { get; set; } - public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } - } - - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + + public bool testFieldBool { get; set; } + public sbyte testFieldSByte { get; set; } + public short testFieldShort { get; set; } + public int testFieldInt { get; set; } + public long testFieldLong { get; set; } + public byte testFieldByte { get; set; } + public ushort testFieldUShort { get; set; } + public uint testFieldUInt { get; set; } + public ulong testFieldULong { get; set; } + public double testFieldDouble { get; set; } + public float testFieldFloat { get; set; } + public decimal testFieldDecimal { get; set; } + public TimeSpan testFieldTimeSpan { get; set; } + public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } + public string testFieldString { get; set; } + public Guid testFieldGuid { get; set; } + + public bool? testFieldBoolNullable { get; set; } + public sbyte? testFieldSByteNullable { get; set; } + public short? testFieldShortNullable { get; set; } + public int? testFieldIntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? testFieldByteNullable { get; set; } + public ushort? testFieldUShortNullable { get; set; } + public uint? testFieldUIntNullable { get; set; } + public ulong? testFieldULongNullable { get; set; } + public double? testFieldDoubleNullable { get; set; } + public float? testFieldFloatNullable { get; set; } + public decimal? testFieldDecimalNullable { get; set; } + public TimeSpan? testFieldTimeSpanNullable { get; set; } + public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } + + public MygisPoint testFieldPoint { get; set; } + public MygisLineString testFieldLineString { get; set; } + public MygisPolygon testFieldPolygon { get; set; } + public MygisMultiPoint testFieldMultiPoint { get; set; } + public MygisMultiLineString testFieldMultiLineString { get; set; } + public MygisMultiPolygon testFieldMultiPolygon { get; set; } + + public TableAllTypeEnumType1 testFieldEnum1 { get; set; } + public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } + public TableAllTypeEnumType2 testFieldEnum2 { get; set; } + public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } + } + + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlDbFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlDbFirstTest.cs index cff6585d..fc0859ae 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlDbFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlDbFirstTest.cs @@ -2,20 +2,24 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.MySql { - public class MySqlDbFirstTest { - [Fact] - public void GetDatabases() { +namespace FreeSql.Tests.MySql +{ + public class MySqlDbFirstTest + { + [Fact] + public void GetDatabases() + { - var t1 = g.mysql.DbFirst.GetDatabases(); + var t1 = g.mysql.DbFirst.GetDatabases(); - } + } - [Fact] - public void GetTablesByDatabase() { + [Fact] + public void GetTablesByDatabase() + { - var t2 = g.mysql.DbFirst.GetTablesByDatabase(g.mysql.DbFirst.GetDatabases()[0]); + var t2 = g.mysql.DbFirst.GetTablesByDatabase(g.mysql.DbFirst.GetDatabases()[0]); - } - } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/ConvertTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/ConvertTest.cs index 79462ef0..86df8ad1 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/ConvertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/ConvertTest.cs @@ -4,143 +4,166 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlExpression { - public class ConvertTest { +namespace FreeSql.Tests.MySqlExpression +{ + public class ConvertTest + { - ISelect select => g.mysql.Select(); + ISelect select => g.mysql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void ToBoolean() { - var data = new List(); - data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); - data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); - } - [Fact] - public void ToByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); - data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); - } - [Fact] - public void ToChar() { - var data = new List(); - data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); - data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); - } - [Fact] - public void ToDateTime() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); - } - [Fact] - public void ToDecimal() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToDouble() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt32() { - var data = new List(); - data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); - data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToSByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); - data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); - } - [Fact] - public void ToSingle() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); - data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); - } - [Fact] - public void ToUInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt32() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); - } + [Fact] + public void ToBoolean() + { + var data = new List(); + data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); + data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); + } + [Fact] + public void ToByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); + data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); + } + [Fact] + public void ToChar() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); + data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); + } + [Fact] + public void ToDateTime() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); + } + [Fact] + public void ToDecimal() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToDouble() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt32() + { + var data = new List(); + data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); + data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToSByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); + data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); + } + [Fact] + public void ToSingle() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); + data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); + } + [Fact] + public void ToUInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt32() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); + } - [Fact] - public void Guid_Parse() { - var data = new List(); - data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); - } + [Fact] + public void Guid_Parse() + { + var data = new List(); + data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); + } - [Fact] - public void Guid_NewGuid() { - var data = new List(); - //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); - } + [Fact] + public void Guid_NewGuid() + { + var data = new List(); + //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); + } - [Fact] - public void Random() { - var data = new List(); - data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); - data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); - } - } + [Fact] + public void Random() + { + var data = new List(); + data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); + data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/DateTimeTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/DateTimeTest.cs index 2b1e8d4c..c1aebfb4 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/DateTimeTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/DateTimeTest.cs @@ -4,652 +4,691 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlExpression { - public class DateTimeTest { - - ISelect select => g.mysql.Select(); - - [Table(Name = "tb_topic111333")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - [Table(Name = "TestTypeInfo333")] - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - public DateTime Time { get; set; } - } - [Table(Name = "TestTypeParentInfo23123")] - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - public DateTime Time2 { get; set; } - } - [Fact] - public void Now() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void UtcNow() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void Date() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) - } - [Fact] - public void TimeOfDay() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) - } - [Fact] - public void DayOfWeek() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) - } - [Fact] - public void Day() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) - } - [Fact] - public void DayOfYear() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) - } - [Fact] - public void Month() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (month(a.`CreateTime`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (month(a__Type.`Time`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (month(a__Type__Parent.`Time2`) > month(now())) - } - [Fact] - public void Year() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (year(a.`CreateTime`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (year(a__Type.`Time`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (year(a__Type__Parent.`Time2`) > year(now())) - } - [Fact] - public void Hour() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (hour(a.`CreateTime`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (hour(a__Type.`Time`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) - } - [Fact] - public void Minute() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (minute(a.`CreateTime`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (minute(a__Type.`Time`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) - } - [Fact] - public void Second() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (second(a.`CreateTime`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (second(a__Type.`Time`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (second(a__Type__Parent.`Time2`) > second(now())) - } - [Fact] - public void Millisecond() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) - } - [Fact] - public void AddDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) - } - [Fact] - public void AddHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) - } - [Fact] - public void AddMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) - } - [Fact] - public void AddMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) - } - [Fact] - public void AddMonths() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) - } - [Fact] - public void AddSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) - } - [Fact] - public void AddTicks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) - } - [Fact] - public void AddYears() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((timestampdiff(microsecond, now(), a.`CreateTime`)) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((timestampdiff(microsecond, now(), a__Type.`Time`)) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((timestampdiff(microsecond, now(), a__Type__Parent.`Time2`)) / 1000000) > 0); - data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_sub(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_sub(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_sub(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`) - } - [Fact] - public void _ЧͬSubtract() { - var data = new List(); - data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((timestampdiff(microsecond, now(), a.`CreateTime`)) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((timestampdiff(microsecond, now(), a__Type.`Time`)) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((timestampdiff(microsecond, now(), a__Type__Parent.`Time2`)) / 1000000) > 0); - data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_sub(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_sub(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_sub(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`) - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) - } - - [Fact] - public void DateTime_Compare() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((a.`CreateTime`) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) - } - [Fact] - public void DateTime_DaysInMonth() { - var data = new List(); - data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) - } - [Fact] - public void DateTime_Equals() { - var data = new List(); - data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void DateTime_IsLeapYear() { - var data = new List(); - data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) - } - [Fact] - public void DateTime_Parse() { - var data = new List(); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) - } - } +namespace FreeSql.Tests.MySqlExpression +{ + public class DateTimeTest + { + + ISelect select => g.mysql.Select(); + + [Table(Name = "tb_topic111333")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + [Table(Name = "TestTypeInfo333")] + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + public DateTime Time { get; set; } + } + [Table(Name = "TestTypeParentInfo23123")] + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + public DateTime Time2 { get; set; } + } + [Fact] + public void Now() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void UtcNow() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void Date() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) + } + [Fact] + public void TimeOfDay() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) + } + [Fact] + public void DayOfWeek() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) + } + [Fact] + public void Day() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) + } + [Fact] + public void DayOfYear() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) + } + [Fact] + public void Month() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (month(a.`CreateTime`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (month(a__Type.`Time`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (month(a__Type__Parent.`Time2`) > month(now())) + } + [Fact] + public void Year() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (year(a.`CreateTime`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (year(a__Type.`Time`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (year(a__Type__Parent.`Time2`) > year(now())) + } + [Fact] + public void Hour() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (hour(a.`CreateTime`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (hour(a__Type.`Time`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) + } + [Fact] + public void Minute() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (minute(a.`CreateTime`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (minute(a__Type.`Time`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) + } + [Fact] + public void Second() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (second(a.`CreateTime`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (second(a__Type.`Time`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (second(a__Type__Parent.`Time2`) > second(now())) + } + [Fact] + public void Millisecond() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) + } + [Fact] + public void AddDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) + } + [Fact] + public void AddHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) + } + [Fact] + public void AddMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) + } + [Fact] + public void AddMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) + } + [Fact] + public void AddMonths() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) + } + [Fact] + public void AddSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) + } + [Fact] + public void AddTicks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) + } + [Fact] + public void AddYears() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((timestampdiff(microsecond, now(), a.`CreateTime`)) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((timestampdiff(microsecond, now(), a__Type.`Time`)) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((timestampdiff(microsecond, now(), a__Type__Parent.`Time2`)) / 1000000) > 0); + data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_sub(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_sub(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_sub(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`) + } + [Fact] + public void _ЧͬSubtract() + { + var data = new List(); + data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((timestampdiff(microsecond, now(), a.`CreateTime`)) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((timestampdiff(microsecond, now(), a__Type.`Time`)) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((timestampdiff(microsecond, now(), a__Type__Parent.`Time2`)) / 1000000) > 0); + data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_sub(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_sub(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_sub(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > a.`CreateTime`) + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) + } + + [Fact] + public void DateTime_Compare() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((a.`CreateTime`) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) + } + [Fact] + public void DateTime_DaysInMonth() + { + var data = new List(); + data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) + } + [Fact] + public void DateTime_Equals() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void DateTime_IsLeapYear() + { + var data = new List(); + data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) + } + [Fact] + public void DateTime_Parse() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/MathTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/MathTest.cs index 321c9212..53490eaa 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/MathTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/MathTest.cs @@ -4,129 +4,153 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlExpression { - public class MathTest { +namespace FreeSql.Tests.MySqlExpression +{ + public class MathTest + { - ISelect select => g.mysql.Select(); + ISelect select => g.mysql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void PI() { - var data = new List(); - data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); - } - [Fact] - public void Abs() { - var data = new List(); - data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Sign() { - var data = new List(); - data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Floor() { - var data = new List(); - data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); - } - [Fact] - public void Ceiling() { - var data = new List(); - data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Round() { - var data = new List(); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); - } - [Fact] - public void Exp() { - var data = new List(); - data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log() { - var data = new List(); - data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log10() { - var data = new List(); - data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Pow() { - var data = new List(); - data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sqrt() { - var data = new List(); - data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Cos() { - var data = new List(); - data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sin() { - var data = new List(); - data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Tan() { - var data = new List(); - data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Acos() { - var data = new List(); - data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Asin() { - var data = new List(); - data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan() { - var data = new List(); - data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan2() { - var data = new List(); - data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Truncate() { - var data = new List(); - data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); - } - } + [Fact] + public void PI() + { + var data = new List(); + data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); + } + [Fact] + public void Abs() + { + var data = new List(); + data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Sign() + { + var data = new List(); + data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Floor() + { + var data = new List(); + data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); + } + [Fact] + public void Ceiling() + { + var data = new List(); + data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Round() + { + var data = new List(); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); + } + [Fact] + public void Exp() + { + var data = new List(); + data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log() + { + var data = new List(); + data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log10() + { + var data = new List(); + data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Pow() + { + var data = new List(); + data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sqrt() + { + var data = new List(); + data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Cos() + { + var data = new List(); + data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sin() + { + var data = new List(); + data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Tan() + { + var data = new List(); + data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Acos() + { + var data = new List(); + data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Asin() + { + var data = new List(); + data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan() + { + var data = new List(); + data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan2() + { + var data = new List(); + data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Truncate() + { + var data = new List(); + data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/OtherTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/OtherTest.cs index f8907726..44345f68 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/OtherTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/OtherTest.cs @@ -5,117 +5,123 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlExpression { - public class OtherTest { +namespace FreeSql.Tests.MySqlExpression +{ + public class OtherTest + { - ISelect select => g.mysql.Select(); + ISelect select => g.mysql.Select(); - public OtherTest() { - - } + public OtherTest() + { - [Fact] - public void Boolean() { - var t1 = select.Where(a => a.testFieldBool == true).ToList(); - var t2 = select.Where(a => a.testFieldBool != true).ToList(); - var t3 = select.Where(a => a.testFieldBool == false).ToList(); - var t4 = select.Where(a => !a.testFieldBool).ToList(); - var t5 = select.Where(a => a.testFieldBool).ToList(); + } - var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList(); - var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); - var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); - var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); - var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList(); - } + [Fact] + public void Boolean() + { + var t1 = select.Where(a => a.testFieldBool == true).ToList(); + var t2 = select.Where(a => a.testFieldBool != true).ToList(); + var t3 = select.Where(a => a.testFieldBool == false).ToList(); + var t4 = select.Where(a => !a.testFieldBool).ToList(); + var t5 = select.Where(a => a.testFieldBool).ToList(); - [Fact] - public void Array() { - int[] nullarr = null; - Assert.Throws(() => { select.Where(a => nullarr.Contains(a.testFieldInt)).ToList(); }); - Assert.Throws(() => { select.Where(a => new int[0].Contains(a.testFieldInt)).ToList(); }); + var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList(); + var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); + var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); + var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); + var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList(); + } - IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); - var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); + [Fact] + public void Array() + { + int[] nullarr = null; + Assert.Throws(() => { select.Where(a => nullarr.Contains(a.testFieldInt)).ToList(); }); + Assert.Throws(() => { select.Where(a => new int[0].Contains(a.testFieldInt)).ToList(); }); - //in not in - var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); - var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); + var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); - var inarray = new[] { 1, 2, 3 }; - var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); - var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); - var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); + //in not in + var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); + var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - //in not in - var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); - var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var inarray = new[] { 1, 2, 3 }; + var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); + var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); + var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); - var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); - var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); - var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); + //in not in + var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); + var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var inarray2 = new List() { 1, 2, 3 }; - var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); - var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); - var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); - } + var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); + var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); + var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + var inarray2 = new List() { 1, 2, 3 }; + var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); + var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); + var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); + } - public bool testFieldBool { get; set; } - public sbyte testFieldSByte { get; set; } - public short testFieldShort { get; set; } - public int testFieldInt { get; set; } - public long testFieldLong { get; set; } - public byte testFieldByte { get; set; } - public ushort testFieldUShort { get; set; } - public uint testFieldUInt { get; set; } - public ulong testFieldULong { get; set; } - public double testFieldDouble { get; set; } - public float testFieldFloat { get; set; } - public decimal testFieldDecimal { get; set; } - public TimeSpan testFieldTimeSpan { get; set; } - public DateTime testFieldDateTime { get; set; } - public byte[] testFieldBytes { get; set; } - public string testFieldString { get; set; } - public Guid testFieldGuid { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - public bool? testFieldBoolNullable { get; set; } - public sbyte? testFieldSByteNullable { get; set; } - public short? testFieldShortNullable { get; set; } - public int? testFieldIntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? testFieldByteNullable { get; set; } - public ushort? testFieldUShortNullable { get; set; } - public uint? testFieldUIntNullable { get; set; } - public ulong? testFieldULongNullable { get; set; } - public double? testFieldDoubleNullable { get; set; } - public float? testFieldFloatNullable { get; set; } - public decimal? testFieldDecimalNullable { get; set; } - public TimeSpan? testFieldTimeSpanNullable { get; set; } - public DateTime? testFieldDateTimeNullable { get; set; } - public Guid? testFieldGuidNullable { get; set; } + public bool testFieldBool { get; set; } + public sbyte testFieldSByte { get; set; } + public short testFieldShort { get; set; } + public int testFieldInt { get; set; } + public long testFieldLong { get; set; } + public byte testFieldByte { get; set; } + public ushort testFieldUShort { get; set; } + public uint testFieldUInt { get; set; } + public ulong testFieldULong { get; set; } + public double testFieldDouble { get; set; } + public float testFieldFloat { get; set; } + public decimal testFieldDecimal { get; set; } + public TimeSpan testFieldTimeSpan { get; set; } + public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } + public string testFieldString { get; set; } + public Guid testFieldGuid { get; set; } - public MygisPoint testFieldPoint { get; set; } - public MygisLineString testFieldLineString { get; set; } - public MygisPolygon testFieldPolygon { get; set; } - public MygisMultiPoint testFieldMultiPoint { get; set; } - public MygisMultiLineString testFieldMultiLineString { get; set; } - public MygisMultiPolygon testFieldMultiPolygon { get; set; } + public bool? testFieldBoolNullable { get; set; } + public sbyte? testFieldSByteNullable { get; set; } + public short? testFieldShortNullable { get; set; } + public int? testFieldIntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? testFieldByteNullable { get; set; } + public ushort? testFieldUShortNullable { get; set; } + public uint? testFieldUIntNullable { get; set; } + public ulong? testFieldULongNullable { get; set; } + public double? testFieldDoubleNullable { get; set; } + public float? testFieldFloatNullable { get; set; } + public decimal? testFieldDecimalNullable { get; set; } + public TimeSpan? testFieldTimeSpanNullable { get; set; } + public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } - public TableAllTypeEnumType1 testFieldEnum1 { get; set; } - public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } - public TableAllTypeEnumType2 testFieldEnum2 { get; set; } - public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } - } + public MygisPoint testFieldPoint { get; set; } + public MygisLineString testFieldLineString { get; set; } + public MygisPolygon testFieldPolygon { get; set; } + public MygisMultiPoint testFieldMultiPoint { get; set; } + public MygisMultiLineString testFieldMultiLineString { get; set; } + public MygisMultiPolygon testFieldMultiPolygon { get; set; } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public TableAllTypeEnumType1 testFieldEnum1 { get; set; } + public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } + public TableAllTypeEnumType2 testFieldEnum2 { get; set; } + public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } + } + + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/StringTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/StringTest.cs index 1b70d10e..558605cc 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/StringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/StringTest.cs @@ -4,693 +4,717 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlExpression { - public class StringTest { - - ISelect select => g.mysql.Select(); - - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - class TestEqualsGuid { - public Guid id { get; set; } - public bool IsDeleted { get; set; } - } - - [Fact] - public void Equals__() { - var list = new List(); - list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); - list.Add(g.mysql.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); - list.Add(g.mysql.Select().Where(a => a.IsDeleted.Equals(false)).ToList()); - } - - [Fact] - public void Empty() { - var data = new List(); - data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ifnull(a.`Title`, '') = '') - } - - [Fact] - public void StartsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) - list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) - } - [Fact] - public void EndsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) - } - [Fact] - public void Contains() { - var list = new List(); - list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) - } - [Fact] - public void ToLower() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void ToUpper() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void Substring() { - var data = new List(); - data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) - } - [Fact] - public void Length() { - var data = new List(); - data.Add(select.Where(a => a.Title.Length == 0).ToList()); - data.Add(select.Where(a => a.Title.Length == 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); - data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) - } - [Fact] - public void IndexOf() { - var data = new List(); - data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) - } - [Fact] - public void PadLeft() { - var data = new List(); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void PadRight() { - var data = new List(); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void Trim() { - var data = new List(); - data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void TrimStart() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) - } - [Fact] - public void TrimEnd() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void Replace() { - var data = new List(); - data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) - } - - [Fact] - public void string_IsNullOrEmpty() { - var data = new List(); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); - data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); - } - } +namespace FreeSql.Tests.MySqlExpression +{ + public class StringTest + { + + ISelect select => g.mysql.Select(); + + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + class TestEqualsGuid + { + public Guid id { get; set; } + public bool IsDeleted { get; set; } + } + + [Fact] + public void Equals__() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); + list.Add(g.mysql.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); + list.Add(g.mysql.Select().Where(a => a.IsDeleted.Equals(false)).ToList()); + } + + [Fact] + public void Empty() + { + var data = new List(); + data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ifnull(a.`Title`, '') = '') + } + + [Fact] + public void StartsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) + list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) + } + [Fact] + public void EndsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) + } + [Fact] + public void Contains() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) + } + [Fact] + public void ToLower() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void ToUpper() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void Substring() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) + } + [Fact] + public void Length() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Length == 0).ToList()); + data.Add(select.Where(a => a.Title.Length == 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); + data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) + } + [Fact] + public void IndexOf() + { + var data = new List(); + data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) + } + [Fact] + public void PadLeft() + { + var data = new List(); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void PadRight() + { + var data = new List(); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void Trim() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void TrimStart() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) + } + [Fact] + public void TrimEnd() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void Replace() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) + } + + [Fact] + public void string_IsNullOrEmpty() + { + var data = new List(); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); + data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/TimeSpanTest.cs b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/TimeSpanTest.cs index cc96d772..8e0a2d4f 100644 --- a/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/TimeSpanTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/MySql/MySqlExpression/TimeSpanTest.cs @@ -4,257 +4,290 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.MySqlExpression { - public class TimeSpanTest { +namespace FreeSql.Tests.MySqlExpression +{ + public class TimeSpanTest + { - ISelect select => g.mysql.Select(); + ISelect select => g.mysql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } - [Fact] - public void Zero() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) - } - [Fact] - public void Days() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) - } - [Fact] - public void Hours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) - } - [Fact] - public void Milliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) - } - [Fact] - public void Minutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) - } - [Fact] - public void Seconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) - } - [Fact] - public void TotalDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) - } - [Fact] - public void TotalHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) - } - [Fact] - public void TotalMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) - } - [Fact] - public void TotalMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) - } - [Fact] - public void TotalSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') - } + public List Types { get; set; } + } + [Fact] + public void Zero() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) + } + [Fact] + public void Days() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) + } + [Fact] + public void Hours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) + } + [Fact] + public void Milliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) + } + [Fact] + public void Minutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) + } + [Fact] + public void Seconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) + } + [Fact] + public void TotalDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) + } + [Fact] + public void TotalHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) + } + [Fact] + public void TotalMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) + } + [Fact] + public void TotalMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) + } + [Fact] + public void TotalSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') + } - [Fact] - public void TimeSpan_Compare() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void TimeSpan_Equals() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromDays() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromHours() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) - } - [Fact] - public void TimeSpan_FromMilliseconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) - } - [Fact] - public void TimeSpan_FromMinutes() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) - } - [Fact] - public void TimeSpan_FromSeconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) - } - [Fact] - public void TimeSpan_FromTicks() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) - } - [Fact] - public void TimeSpan_Parse() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) - } - } + [Fact] + public void TimeSpan_Compare() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void TimeSpan_Equals() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromDays() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromHours() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) + } + [Fact] + public void TimeSpan_FromMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) + } + [Fact] + public void TimeSpan_FromMinutes() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) + } + [Fact] + public void TimeSpan_FromSeconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) + } + [Fact] + public void TimeSpan_FromTicks() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) + } + [Fact] + public void TimeSpan_Parse() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleDeleteTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleDeleteTest.cs index ece0e712..881c176c 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleDeleteTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleDeleteTest.cs @@ -4,86 +4,95 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.Oracle { - public class OracleDeleteTest { +namespace FreeSql.Tests.Oracle +{ + public class OracleDeleteTest + { - IDelete delete => g.oracle.Delete(); //�������� + IDelete delete => g.oracle.Delete(); //�������� - [Table(Name = "tb_topic22211")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } + [Table(Name = "tb_topic22211")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void Dywhere() { - Assert.Null(g.oracle.Delete().ToSql()); - var sql = g.oracle.Delete(new[] { 1, 2 }).ToSql(); - Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1 OR \"ID\" = 2)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(g.oracle.Delete().ToSql()); + var sql = g.oracle.Delete(new[] { 1, 2 }).ToSql(); + Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1 OR \"ID\" = 2)", sql); - sql = g.oracle.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); - Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1)", sql); + sql = g.oracle.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); + Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1)", sql); - sql = g.oracle.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); - Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1 OR \"ID\" = 2)", sql); + sql = g.oracle.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); + Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1 OR \"ID\" = 2)", sql); - sql = g.oracle.Delete(new { id = 1 }).ToSql(); - Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1)", sql); - } + sql = g.oracle.Delete(new { id = 1 }).ToSql(); + Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1)", sql); + } - [Fact] - public void Where() { - var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1)", sql); + [Fact] + public void Where() + { + var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1)", sql); - sql = delete.Where("id = :id", new { id = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (id = :id)", sql); + sql = delete.Where("id = :id", new { id = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (id = :id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = delete.Where(item).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = delete.Where(item).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = delete.Where(items).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + sql = delete.Where(items).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"TB_TOPIC22211\" WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - var id = g.oracle.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteIdentity(); - Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); - } - [Fact] - public void ExecuteDeleted() { + var id = g.oracle.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteIdentity(); + Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); + } + [Fact] + public void ExecuteDeleted() + { - //var item = g.oracle.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteInserted(); - //Assert.Equal(item[0].Id, delete.Where(a => a.Id == item[0].Id).ExecuteDeleted()[0].Id); - } + //var item = g.oracle.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteInserted(); + //Assert.Equal(item[0].Id, delete.Where(a => a.Id == item[0].Id).ExecuteDeleted()[0].Id); + } - [Fact] - public void AsTable() { - Assert.Null(g.oracle.Delete().ToSql()); - var sql = g.oracle.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"ID\" = 1 OR \"ID\" = 2)", sql); + [Fact] + public void AsTable() + { + Assert.Null(g.oracle.Delete().ToSql()); + var sql = g.oracle.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"ID\" = 1 OR \"ID\" = 2)", sql); - sql = g.oracle.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"ID\" = 1)", sql); + sql = g.oracle.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"ID\" = 1)", sql); - sql = g.oracle.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"ID\" = 1 OR \"ID\" = 2)", sql); + sql = g.oracle.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"ID\" = 1 OR \"ID\" = 2)", sql); - sql = g.oracle.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"ID\" = 1)", sql); - } - } + sql = g.oracle.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"ID\" = 1)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleInsertTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleInsertTest.cs index 331a9703..a87cedbf 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleInsertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleInsertTest.cs @@ -4,33 +4,37 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.Oracle { - public class OracleInsertTest { +namespace FreeSql.Tests.Oracle +{ + public class OracleInsertTest + { - IInsert insert => g.oracle.Insert(); //�������� + IInsert insert => g.oracle.Insert(); //�������� - [Table(Name = "tb_topic_insert")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - - [Fact] - public void AppendData() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + [Table(Name = "tb_topic_insert")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - var data = new List(); - var sql = insert.AppendData(items.First()).ToSql(); - Assert.Equal("INSERT INTO \"TB_TOPIC_INSERT\"(\"CLICKS\", \"TITLE\", \"CREATETIME\") VALUES(:Clicks_0, :Title_0, :CreateTime_0)", sql); - data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + [Fact] + public void AppendData() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - sql = insert.AppendData(items).ToSql(); - Assert.Equal(@"INSERT ALL + var data = new List(); + var sql = insert.AppendData(items.First()).ToSql(); + Assert.Equal("INSERT INTO \"TB_TOPIC_INSERT\"(\"CLICKS\", \"TITLE\", \"CREATETIME\") VALUES(:Clicks_0, :Title_0, :CreateTime_0)", sql); + data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + + sql = insert.AppendData(items).ToSql(); + Assert.Equal(@"INSERT ALL INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_0, :Title_0, :CreateTime_0) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_1, :Title_1, :CreateTime_1) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_2, :Title_2, :CreateTime_2) @@ -42,10 +46,10 @@ INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_7 INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_8, :Title_8, :CreateTime_8) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_9, :Title_9, :CreateTime_9) SELECT 1 FROM DUAL", sql); - data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + data.Add(insert.AppendData(items.First()).ExecuteIdentity()); - sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal(@"INSERT ALL INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_0) INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_1) INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_2) @@ -57,10 +61,10 @@ INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_7) INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_8) INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_9) SELECT 1 FROM DUAL", sql); - data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + data.Add(insert.AppendData(items.First()).ExecuteIdentity()); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal(@"INSERT ALL INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_0, :Title_0) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_1, :Title_1) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_2, :Title_2) @@ -72,17 +76,18 @@ INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_7, :Title_7) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_8, :Title_8) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_9, :Title_9) SELECT 1 FROM DUAL", sql); - data.Add(insert.AppendData(items.First()).ExecuteIdentity()); - } + data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + } - [Fact] - public void InsertColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + [Fact] + public void InsertColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - var data = new List(); - var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal(@"INSERT ALL + var data = new List(); + var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal(@"INSERT ALL INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_0) INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_1) INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_2) @@ -94,10 +99,10 @@ INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_7) INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_8) INTO ""TB_TOPIC_INSERT""(""TITLE"") VALUES(:Title_9) SELECT 1 FROM DUAL", sql); - data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + data.Add(insert.AppendData(items.First()).ExecuteIdentity()); - sql = insert.AppendData(items).InsertColumns(a =>new { a.Title, a.Clicks }).ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql(); + Assert.Equal(@"INSERT ALL INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_0, :Title_0) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_1, :Title_1) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_2, :Title_2) @@ -109,16 +114,17 @@ INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_7, :Title_7) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_8, :Title_8) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_9, :Title_9) SELECT 1 FROM DUAL", sql); - data.Add(insert.AppendData(items.First()).ExecuteIdentity()); - } - [Fact] - public void IgnoreColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + } + [Fact] + public void IgnoreColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - var data = new List(); - var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal(@"INSERT ALL + var data = new List(); + var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal(@"INSERT ALL INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_0, :Title_0) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_1, :Title_1) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_2, :Title_2) @@ -130,10 +136,10 @@ INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_7, :Title_7) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_8, :Title_8) INTO ""TB_TOPIC_INSERT""(""CLICKS"", ""TITLE"") VALUES(:Clicks_9, :Title_9) SELECT 1 FROM DUAL", sql); - data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + data.Add(insert.AppendData(items.First()).ExecuteIdentity()); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); + Assert.Equal(@"INSERT ALL INTO ""TB_TOPIC_INSERT""(""CLICKS"") VALUES(:Clicks_0) INTO ""TB_TOPIC_INSERT""(""CLICKS"") VALUES(:Clicks_1) INTO ""TB_TOPIC_INSERT""(""CLICKS"") VALUES(:Clicks_2) @@ -145,41 +151,45 @@ INTO ""TB_TOPIC_INSERT""(""CLICKS"") VALUES(:Clicks_7) INTO ""TB_TOPIC_INSERT""(""CLICKS"") VALUES(:Clicks_8) INTO ""TB_TOPIC_INSERT""(""CLICKS"") VALUES(:Clicks_9) SELECT 1 FROM DUAL", sql); - data.Add(insert.AppendData(items.First()).ExecuteIdentity()); - } - [Fact] - public void ExecuteAffrows() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + data.Add(insert.AppendData(items.First()).ExecuteIdentity()); + } + [Fact] + public void ExecuteAffrows() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); - } - [Fact] - public void ExecuteIdentity() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); + } + [Fact] + public void ExecuteIdentity() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); - } - [Fact] - public void ExecuteInserted() { - //var items = new List(); - //for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); + } + [Fact] + public void ExecuteInserted() + { + //var items = new List(); + //for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - //var items2 = insert.AppendData(items).ExecuteInserted(); - } + //var items2 = insert.AppendData(items).ExecuteInserted(); + } - [Fact] - public void AsTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + [Fact] + public void AsTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"CLICKS\", \"TITLE\", \"CREATETIME\") VALUES(:Clicks_0, :Title_0, :CreateTime_0)", sql); + var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"CLICKS\", \"TITLE\", \"CREATETIME\") VALUES(:Clicks_0, :Title_0, :CreateTime_0)", sql); - sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal(@"INSERT ALL INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_0, :Title_0, :CreateTime_0) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_1, :Title_1, :CreateTime_1) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_2, :Title_2, :CreateTime_2) @@ -192,8 +202,8 @@ INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clic INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"", ""CREATETIME"") VALUES(:Clicks_9, :Title_9, :CreateTime_9) SELECT 1 FROM DUAL", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal(@"INSERT ALL INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_0) INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_1) INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_2) @@ -206,8 +216,8 @@ INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_8) INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_9) SELECT 1 FROM DUAL", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal(@"INSERT ALL INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_0, :Title_0) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_1, :Title_1) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_2, :Title_2) @@ -220,8 +230,8 @@ INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_8, :Title_8) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_9, :Title_9) SELECT 1 FROM DUAL", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal(@"INSERT ALL INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_0) INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_1) INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_2) @@ -234,8 +244,8 @@ INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_8) INTO ""Topic_InsertAsTable""(""TITLE"") VALUES(:Title_9) SELECT 1 FROM DUAL", sql); - sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal(@"INSERT ALL INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_0, :Title_0) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_1, :Title_1) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_2, :Title_2) @@ -248,8 +258,8 @@ INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_8, :Title_8) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_9, :Title_9) SELECT 1 FROM DUAL", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal(@"INSERT ALL INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_0, :Title_0) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_1, :Title_1) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_2, :Title_2) @@ -262,8 +272,8 @@ INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_8, :Title_8) INTO ""Topic_InsertAsTable""(""CLICKS"", ""TITLE"") VALUES(:Clicks_9, :Title_9) SELECT 1 FROM DUAL", sql); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal(@"INSERT ALL + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal(@"INSERT ALL INTO ""Topic_InsertAsTable""(""CLICKS"") VALUES(:Clicks_0) INTO ""Topic_InsertAsTable""(""CLICKS"") VALUES(:Clicks_1) INTO ""Topic_InsertAsTable""(""CLICKS"") VALUES(:Clicks_2) @@ -275,6 +285,6 @@ INTO ""Topic_InsertAsTable""(""CLICKS"") VALUES(:Clicks_7) INTO ""Topic_InsertAsTable""(""CLICKS"") VALUES(:Clicks_8) INTO ""Topic_InsertAsTable""(""CLICKS"") VALUES(:Clicks_9) SELECT 1 FROM DUAL", sql); - } - } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleSelectTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleSelectTest.cs index 22397b90..cafc9e54 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleSelectTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleSelectTest.cs @@ -4,1112 +4,1182 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.Oracle { - public class OracleSelectTest { - - ISelect select => g.oracle.Select(); - - [Table(Name = "tb_topic22")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - - class TopicInserts { - public Guid Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - public partial class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } - - public virtual ICollection Tags { get; set; } - } - public partial class Song_tag { - public int Song_id { get; set; } - public virtual Song Song { get; set; } - - public int Tag_id { get; set; } - public virtual Tag Tag { get; set; } - } - public partial class Tag { - [Column(IsIdentity = true)] - public int Id { get; set; } - public int? Parent_id { get; set; } - public virtual Tag Parent { get; set; } - - public decimal? Ddd { get; set; } - public string Name { get; set; } - - public virtual ICollection Songs { get; set; } - public virtual ICollection Tags { get; set; } - } - - [Fact] - public void AsSelect() { - //OneToOne、ManyToOne - var t0 = g.oracle.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 - //FROM `Tag` a - //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` - //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` - //WHERE (a__Parent__Parent.`Name` = '粤语') - - //OneToMany - var t1 = g.oracle.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` - //FROM `Tag` a - //WHERE (exists(SELECT 1 - // FROM `Tag` t - // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` - // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) - // limit 0,1)) - - //ManyToMany - var t2 = g.oracle.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); - //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` - //FROM `Song` a - //WHERE(exists(SELECT 1 - // FROM `Song_tag` Mt_Ms - // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 - // FROM `Tag` t - // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) - // limit 0, 1)) - // limit 0, 1)) - } - - [Fact] - public void Lazy() { - var tags = g.oracle.Select().Where(a => a.Parent.Name == "xxx") - .LeftJoin(a => a.Parent_id == a.Parent.Id) - .ToSql(); - - var songs = g.oracle.Select().Limit(10).ToList(); - } - - [Fact] - public void ToDataTable() { - var items = new List(); - for (var a = 0; a < 11; a++) items.Add(new TopicInserts { Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - - //Assert.Equal(1, g.oracle.Insert().AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(11, g.oracle.Insert().AppendData(items).ExecuteAffrows()); - - //items = Enumerable.Range(0, 9989).Select(a => new TopicInserts { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - //Assert.Equal(9989, g.oracle.Insert(items).ExecuteAffrows()); - - var dt1 = select.Limit(10).ToDataTable(); - var dt2 = select.Limit(10).ToDataTable("id, 111222"); - var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); - } - class TestDto { - public int id { get; set; } - public string name { get; set; } //这是join表的属性 - public int ParentId { get; set; } //这是join表的属性 - } - [Fact] - public void ToList() { - - var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto2 = select.Limit(10).ToList(a => new TestDto()); - var testDto3 = select.Limit(10).ToList(a => new TestDto { }); - var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); - - var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); - var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); - var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); - - g.oracle.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); - var testGuidId5 = g.oracle.Select().ToList(); - var testGuidId6 = g.oracle.Select().ToList(a => a.id); - - var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); - var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); - } - class TestGuidIdToList { - public Guid id { get; set; } - public string title { get; set; } = Guid.NewGuid().ToString(); - } - [Fact] - public void ToOne() { - var testnotfind = select.Where("1=2").First(a => a.CreateTime); - Assert.Equal(default(DateTime), testnotfind); - } - [Fact] - public void ToSql() { - } - [Fact] - public void Any() { - var count = select.Where(a => 1 == 1).Count(); - Assert.False(select.Where(a => 1 == 2).Any()); - Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); - - var sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && - select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - //.Offset(a.Id) - .Any() - ).Any(c => c.Id == a.Id + 10) - ); - var sql2222Tolist = sql2222.ToList(); - - var collectionSelect = select.Where(a => - a.Type.Guid == a.TypeGuid && - a.Type.Parent.Id == a.Type.ParentId && - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) - ); - collectionSelect.ToList(); - } - [Fact] - public void Count() { - var count = select.Where(a => 1 == 1).Count(); - select.Where(a => 1 == 1).Count(out var count2); - Assert.Equal(count, count2); - Assert.Equal(0, select.Where(a => 1 == 2).Count()); - } - [Fact] - public void Master() { - Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); - } - [Fact] - public void From() { - var query2 = select.From((s, b) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - ); - var sql2 = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\"", sql2); - query2.ToList(); - - var query3 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id) - ); - var sql3 = query3.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" c ON b.\"PARENTID\" = c.\"ID\"", sql3); - query3.ToList(); - } - [Fact] - public void LeftJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); - query.ToList(); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\"", sql); - query.ToList(); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" c ON c.\"ID\" = a__Type.\"PARENTID\"", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" c ON b.\"PARENTID\" = c.\"ID\"", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.LeftJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\""); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.LeftJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", sql); - query.ToList(); - } - [Fact] - public void InnerJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); - query.ToList(); - - //������� - query = select - .InnerJoin(a => a.Type.Guid == a.TypeGuid) - .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" INNER JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\"", sql); - query.ToList(); - - query = select - .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .InnerJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" INNER JOIN \"TESTTYPEPARENTINFO\" c ON c.\"ID\" = a__Type.\"PARENTID\"", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .InnerJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\" INNER JOIN \"TESTTYPEPARENTINFO\" c ON b.\"PARENTID\" = c.\"ID\"", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.InnerJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\""); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.InnerJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", sql); - query.ToList(); - - } - [Fact] - public void RightJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); - query.ToList(); - - //������� - query = select - .RightJoin(a => a.Type.Guid == a.TypeGuid) - .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" RIGHT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\"", sql); - query.ToList(); - - query = select - .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .RightJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" RIGHT JOIN \"TESTTYPEPARENTINFO\" c ON c.\"ID\" = a__Type.\"PARENTID\"", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .RightJoin(a => a.TypeGuid == b.Guid) - .RightJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\" RIGHT JOIN \"TESTTYPEPARENTINFO\" c ON b.\"PARENTID\" = c.\"ID\"", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.RightJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\""); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"", sql); - query.ToList(); - - query = select.RightJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", sql); - query.ToList(); - - } - [Fact] - public void Where() { - var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); - var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); - var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); - - var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.Where(a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"ID\" = 10)", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE ((a.\"ID\" = 10 AND a.\"ID\" > 10 OR a.\"CLICKS\" > 100))", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"ID\" = 10) AND (a.\"CLICKS\" > 100)", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" WHERE (a__Type.\"NAME\" = 'typeTitle')", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" WHERE (a__Type.\"NAME\" = 'typeTitle' AND a__Type.\"GUID\" = a.\"TYPEGUID\")", sql); - query.ToList(); - - query = select.Where(a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"NAME\" = 'tparent')", sql); - query.ToList(); - - //���û�е������ԣ��򵥶������ - query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b WHERE (b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'typeTitle')", sql); - query.ToList(); - - query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b WHERE (b.\"NAME\" = 'typeTitle' AND b.\"GUID\" = a.\"TYPEGUID\")", sql); - query.ToList(); - - query = select.Where((a, b, c) => c.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEPARENTINFO\" c WHERE (c.\"NAME\" = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .Where(a => a.Id == 10 && c.Name == "xxx") - .Where(a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b, \"TESTTYPEPARENTINFO\" c WHERE (a.\"ID\" = 10 AND c.\"NAME\" = 'xxx') AND (b.\"PARENTID\" = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.Where("a.\"CLICKS\" > 100 and a.\"ID\" = :id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"CLICKS\" > 100 and a.\"ID\" = :id)", sql); - query.ToList(); - } - [Fact] - public void WhereIf() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.WhereIf(true, a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"ID\" = 10)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE ((a.\"ID\" = 10 AND a.\"ID\" > 10 OR a.\"CLICKS\" > 100))", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"ID\" = 10) AND (a.\"CLICKS\" > 100)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" WHERE (a__Type.\"NAME\" = 'typeTitle')", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" WHERE (a__Type.\"NAME\" = 'typeTitle' AND a__Type.\"GUID\" = a.\"TYPEGUID\")", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"NAME\" = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(true, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b, \"TESTTYPEPARENTINFO\" c WHERE (a.\"ID\" = 10 AND c.\"NAME\" = 'xxx') AND (b.\"PARENTID\" = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(true, "a.\"CLICKS\" > 100 and a.\"ID\" = :id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"CLICKS\" > 100 and a.\"ID\" = :id)", sql); - query.ToList(); - - // ==========================================WhereIf(false) - - //����е�������a.Type��a.Type.Parent ���ǵ������� - query = select.WhereIf(false, a => a.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - query2 = select.From((s, b, c) => s - .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(false, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b, \"TESTTYPEPARENTINFO\" c", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(false, "a.\"CLICKS\" > 100 and a.\"ID\" = :id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); - query.ToList(); - } - [Fact] - public void WhereExists() { - var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); - - sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - - //.Offset(a.Id) - - .Any() - ).Any() - ).ToList(); - } - [Fact] - public void GroupBy() { - var groupby = select.From((s, b, c) => s - .Where(a => a.Id == 1) - ) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()) - .Offset(10) - .Limit(2) - .ToList(a => new { - a.Key.tt2, - cou1 = a.Count(), - arg1 = a.Avg(a.Key.mod4), - ccc2 = a.Key.tt2 ?? "now()", - //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") - ccc3 = a.Max(a.Value.Item3.Id) - }); - - var testpid1 = g.oracle.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); - g.oracle.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); - - var aggsql1 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist1 = select - .GroupBy(a => a.Title) - .ToList(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToSql(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToList(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql3 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid), - sum3 = b.Sum(b.Value.Type.Parent.Id) - }); - } - [Fact] - public void ToAggregate() { - var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); - } - [Fact] - public void OrderBy() { - var sql = select.Offset(10).OrderBy(a => new Random().NextDouble()).ToList(); - } - [Fact] - public void Skip_Offset() { - var sql = select.Offset(10).ToList(); - } - [Fact] - public void Take_Limit() { - var sql = select.Limit(10).ToList(); - } - [Fact] - public void Page() { - var sql1 = select.Page(1, 10).ToList(); - var sql2 = select.Page(2, 10).ToList(); - var sql3 = select.Page(3, 10).ToList(); - - var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); - var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); - var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); - } - [Fact] - public void Distinct() { - var t1 = select.Distinct().ToList(a => a.Title); - var t2 = select.Distinct().Limit(10).ToList(a => a.Title); - } - - [Fact] - public void Sum() { - } - [Fact] - public void Min() { - } - [Fact] - public void Max() { - } - [Fact] - public void Avg() { - } - [Fact] - public void As() { - } - - [Fact] - public void AsTable() { - - var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); - - Func tableRule = (type, oldname) => { - if (type == typeof(Topic)) return oldname + "AsTable1"; - else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; - return oldname + "AsTable"; - }; - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\"", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx'", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" b ON b.\"GUID\" = a.\"TYPEGUID\"", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" b ON b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'xxx'", sql); - - query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\"", sql); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" c ON c.\"ID\" = a__Type.\"PARENTID\"", sql); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" b ON a.\"TYPEGUID\" = b.\"GUID\" LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" c ON b.\"PARENTID\" = c.\"ID\"", sql); - - //������϶����㲻�� - query = select.LeftJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"", sql); - - query = select.LeftJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", new { bname = "xxx" }).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", sql); - } - - public class TiOtmModel1 { - [Column(IsIdentity = true)] - public int id { get; set; } - public virtual TiOtmModel2 model2 { get; set; } - - public string m1name { get; set; } - } - public class TiOtmModel2 { - [Column(IsPrimary = true)] - public int model2id { get; set; } - public virtual TiOtmModel1 model1 { get; set; } - - public string m2setting { get; set; } - - public List childs { get; set; } - } - public class TiOtmModel3 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model2111Idaaa { get; set; } - public string title { get; set; } - - public List childs2 { get; set; } - } - public class TiOtmModel4 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model3333Id333 { get; set; } - public string title444 { get; set; } - } - - [Fact] - public void Include_OneToMany() { - var model1 = new TiOtmModel1 { m1name = DateTime.Now.Second.ToString() }; - model1.id = (int)g.oracle.Insert(model1).ExecuteIdentity(); - var model2 = new TiOtmModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; - g.oracle.Insert(model2).ExecuteAffrows(); - - var model3_1 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; - model3_1.id = (int)g.oracle.Insert(model3_1).ExecuteIdentity(); - var model3_2 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; - model3_2.id = (int)g.oracle.Insert(model3_2).ExecuteIdentity(); - var model3_3 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; - model3_3.id = (int)g.oracle.Insert(model3_2).ExecuteIdentity(); - - var model4s = new[] { - new TiOtmModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, - new TiOtmModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, - new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, - new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, - new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } - }; - Assert.Equal(5, g.oracle.Insert(model4s).ExecuteAffrows()); - - var t0 = g.oracle.Select() - .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t1 = g.oracle.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t2 = g.oracle.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - - var t00 = g.oracle.Select() - .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t11 = g.oracle.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t22 = g.oracle.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - } - - public class TiOtmModel11 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2id { get; set; } - public string m3setting { get; set; } - public TiOtmModel22 model2 { get; set; } - public string m1name { get; set; } - } - - public class TiOtmModel22 { - [Column(IsIdentity = true)] - public int id { get; set; } - public string m2setting { get; set; } - public List childs { get; set; } - } - public class TiOtmModel33 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2Id { get; set; } - public string title { get; set; } - public string setting { get; set; } - } - [Fact] - public void Include_OneToMany2() { - string setting = "x"; - var model2 = new TiOtmModel22 { m2setting = DateTime.Now.Second.ToString() }; - model2.id = (int)g.oracle.Insert(model2).ExecuteIdentity(); - - var model3s = new[] - { - new TiOtmModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, - new TiOtmModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, - new TiOtmModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} - }; - Assert.Equal(3, g.oracle.Insert(model3s).ExecuteAffrows()); - - var model1 = new TiOtmModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; - model1.id = (int)g.oracle.Insert(model1).ExecuteIdentity(); - - var t1 = g.oracle.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - - var t11 = g.oracle.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - } - - [Fact] - public void Include_OneToChilds() { - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_中国" - }; - tag1.Id = (int)g.oracle.Insert(tag1).ExecuteIdentity(); - var tag1_1 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_北京" - }; - tag1_1.Id = (int)g.oracle.Insert(tag1_1).ExecuteIdentity(); - var tag1_2 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_上海" - }; - tag1_2.Id = (int)g.oracle.Insert(tag1_2).ExecuteIdentity(); - - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_美国" - }; - tag2.Id = (int)g.oracle.Insert(tag2).ExecuteIdentity(); - var tag2_1 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_纽约" - }; - tag2_1.Id = (int)g.oracle.Insert(tag2_1).ExecuteIdentity(); - var tag2_2 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_华盛顿" - }; - tag2_2.Id = (int)g.oracle.Insert(tag2_2).ExecuteIdentity(); - - var tags0 = g.oracle.Select() - .Include(a => a.Parent) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags1 = g.oracle.Select() - .IncludeMany(a => a.Tags) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags2 = g.oracle.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags3 = g.oracle.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags11 = g.oracle.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags22 = g.oracle.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags33 = g.oracle.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - } - - [Fact] - public void Include_ManyToMany() { - - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_01_中国" - }; - tag1.Id = (int)g.oracle.Insert(tag1).ExecuteIdentity(); - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_02_美国" - }; - tag2.Id = (int)g.oracle.Insert(tag2).ExecuteIdentity(); - var tag3 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_03_日本" - }; - tag3.Id = (int)g.oracle.Insert(tag3).ExecuteIdentity(); - - var song1 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_01_我是中国人.mp3", - Url = "http://ww.baidu.com/" - }; - song1.Id = (int)g.oracle.Insert(song1).ExecuteIdentity(); - var song2 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_02_爱你一万年.mp3", - Url = "http://ww.163.com/" - }; - song2.Id = (int)g.oracle.Insert(song2).ExecuteIdentity(); - var song3 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_03_千年等一回.mp3", - Url = "http://ww.sina.com/" - }; - song3.Id = (int)g.oracle.Insert(song3).ExecuteIdentity(); - - g.oracle.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.oracle.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.oracle.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.oracle.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.oracle.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.oracle.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); - - var songs1 = g.oracle.Select() - .IncludeMany(a => a.Tags) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs1.Count); - Assert.Equal(2, songs1[0].Tags.Count); - Assert.Equal(1, songs1[1].Tags.Count); - Assert.Equal(3, songs1[2].Tags.Count); - - var songs2 = g.oracle.Select() - .IncludeMany(a => a.Tags, - then => then.IncludeMany(t => t.Songs)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs2.Count); - Assert.Equal(2, songs2[0].Tags.Count); - Assert.Equal(1, songs2[1].Tags.Count); - Assert.Equal(3, songs2[2].Tags.Count); - - var tags3 = g.oracle.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - - - var songs11 = g.oracle.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs11.Count); - Assert.Equal(1, songs11[0].Tags.Count); - Assert.Equal(1, songs11[1].Tags.Count); - Assert.Equal(1, songs11[2].Tags.Count); - - var songs22 = g.oracle.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.IncludeMany(t => t.Songs.Take(1))) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs22.Count); - Assert.Equal(1, songs22[0].Tags.Count); - Assert.Equal(1, songs22[1].Tags.Count); - Assert.Equal(1, songs22[2].Tags.Count); - - var tags33 = g.oracle.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs.Take(1)) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - } - } +namespace FreeSql.Tests.Oracle +{ + public class OracleSelectTest + { + + ISelect select => g.oracle.Select(); + + [Table(Name = "tb_topic22")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + + class TopicInserts + { + public Guid Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + public partial class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } + + public virtual ICollection Tags { get; set; } + } + public partial class Song_tag + { + public int Song_id { get; set; } + public virtual Song Song { get; set; } + + public int Tag_id { get; set; } + public virtual Tag Tag { get; set; } + } + public partial class Tag + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public int? Parent_id { get; set; } + public virtual Tag Parent { get; set; } + + public decimal? Ddd { get; set; } + public string Name { get; set; } + + public virtual ICollection Songs { get; set; } + public virtual ICollection Tags { get; set; } + } + + [Fact] + public void AsSelect() + { + //OneToOne、ManyToOne + var t0 = g.oracle.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 + //FROM `Tag` a + //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` + //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` + //WHERE (a__Parent__Parent.`Name` = '粤语') + + //OneToMany + var t1 = g.oracle.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` + //FROM `Tag` a + //WHERE (exists(SELECT 1 + // FROM `Tag` t + // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` + // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) + // limit 0,1)) + + //ManyToMany + var t2 = g.oracle.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); + //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` + //FROM `Song` a + //WHERE(exists(SELECT 1 + // FROM `Song_tag` Mt_Ms + // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 + // FROM `Tag` t + // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) + // limit 0, 1)) + // limit 0, 1)) + } + + [Fact] + public void Lazy() + { + var tags = g.oracle.Select().Where(a => a.Parent.Name == "xxx") + .LeftJoin(a => a.Parent_id == a.Parent.Id) + .ToSql(); + + var songs = g.oracle.Select().Limit(10).ToList(); + } + + [Fact] + public void ToDataTable() + { + var items = new List(); + for (var a = 0; a < 11; a++) items.Add(new TopicInserts { Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + + //Assert.Equal(1, g.oracle.Insert().AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(11, g.oracle.Insert().AppendData(items).ExecuteAffrows()); + + //items = Enumerable.Range(0, 9989).Select(a => new TopicInserts { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + //Assert.Equal(9989, g.oracle.Insert(items).ExecuteAffrows()); + + var dt1 = select.Limit(10).ToDataTable(); + var dt2 = select.Limit(10).ToDataTable("id, 111222"); + var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); + } + class TestDto + { + public int id { get; set; } + public string name { get; set; } //这是join表的属性 + public int ParentId { get; set; } //这是join表的属性 + } + [Fact] + public void ToList() + { + + var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto2 = select.Limit(10).ToList(a => new TestDto()); + var testDto3 = select.Limit(10).ToList(a => new TestDto { }); + var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); + + var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); + var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); + var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); + + g.oracle.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); + var testGuidId5 = g.oracle.Select().ToList(); + var testGuidId6 = g.oracle.Select().ToList(a => a.id); + + var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); + var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); + } + class TestGuidIdToList + { + public Guid id { get; set; } + public string title { get; set; } = Guid.NewGuid().ToString(); + } + [Fact] + public void ToOne() + { + var testnotfind = select.Where("1=2").First(a => a.CreateTime); + Assert.Equal(default(DateTime), testnotfind); + } + [Fact] + public void ToSql() + { + } + [Fact] + public void Any() + { + var count = select.Where(a => 1 == 1).Count(); + Assert.False(select.Where(a => 1 == 2).Any()); + Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); + + var sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && + select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + //.Offset(a.Id) + .Any() + ).Any(c => c.Id == a.Id + 10) + ); + var sql2222Tolist = sql2222.ToList(); + + var collectionSelect = select.Where(a => + a.Type.Guid == a.TypeGuid && + a.Type.Parent.Id == a.Type.ParentId && + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) + ); + collectionSelect.ToList(); + } + [Fact] + public void Count() + { + var count = select.Where(a => 1 == 1).Count(); + select.Where(a => 1 == 1).Count(out var count2); + Assert.Equal(count, count2); + Assert.Equal(0, select.Where(a => 1 == 2).Count()); + } + [Fact] + public void Master() + { + Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); + } + [Fact] + public void From() + { + var query2 = select.From((s, b) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + ); + var sql2 = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\"", sql2); + query2.ToList(); + + var query3 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id) + ); + var sql3 = query3.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" c ON b.\"PARENTID\" = c.\"ID\"", sql3); + query3.ToList(); + } + [Fact] + public void LeftJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); + query.ToList(); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\"", sql); + query.ToList(); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" c ON c.\"ID\" = a__Type.\"PARENTID\"", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" c ON b.\"PARENTID\" = c.\"ID\"", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.LeftJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\""); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.LeftJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", sql); + query.ToList(); + } + [Fact] + public void InnerJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); + query.ToList(); + + //������� + query = select + .InnerJoin(a => a.Type.Guid == a.TypeGuid) + .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" INNER JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\"", sql); + query.ToList(); + + query = select + .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .InnerJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" INNER JOIN \"TESTTYPEPARENTINFO\" c ON c.\"ID\" = a__Type.\"PARENTID\"", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .InnerJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\" INNER JOIN \"TESTTYPEPARENTINFO\" c ON b.\"PARENTID\" = c.\"ID\"", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.InnerJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\""); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.InnerJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a INNER JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", sql); + query.ToList(); + + } + [Fact] + public void RightJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b ON b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); + query.ToList(); + + //������� + query = select + .RightJoin(a => a.Type.Guid == a.TypeGuid) + .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" RIGHT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\"", sql); + query.ToList(); + + query = select + .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .RightJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" RIGHT JOIN \"TESTTYPEPARENTINFO\" c ON c.\"ID\" = a__Type.\"PARENTID\"", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .RightJoin(a => a.TypeGuid == b.Guid) + .RightJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b ON a.\"TYPEGUID\" = b.\"GUID\" RIGHT JOIN \"TESTTYPEPARENTINFO\" c ON b.\"PARENTID\" = c.\"ID\"", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.RightJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\""); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"", sql); + query.ToList(); + + query = select.RightJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a RIGHT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", sql); + query.ToList(); + + } + [Fact] + public void Where() + { + var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); + var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); + var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); + + var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.Where(a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"ID\" = 10)", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE ((a.\"ID\" = 10 AND a.\"ID\" > 10 OR a.\"CLICKS\" > 100))", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"ID\" = 10) AND (a.\"CLICKS\" > 100)", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" WHERE (a__Type.\"NAME\" = 'typeTitle')", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" WHERE (a__Type.\"NAME\" = 'typeTitle' AND a__Type.\"GUID\" = a.\"TYPEGUID\")", sql); + query.ToList(); + + query = select.Where(a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"NAME\" = 'tparent')", sql); + query.ToList(); + + //���û�е������ԣ��򵥶������ + query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b WHERE (b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'typeTitle')", sql); + query.ToList(); + + query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b WHERE (b.\"NAME\" = 'typeTitle' AND b.\"GUID\" = a.\"TYPEGUID\")", sql); + query.ToList(); + + query = select.Where((a, b, c) => c.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEPARENTINFO\" c WHERE (c.\"NAME\" = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .Where(a => a.Id == 10 && c.Name == "xxx") + .Where(a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b, \"TESTTYPEPARENTINFO\" c WHERE (a.\"ID\" = 10 AND c.\"NAME\" = 'xxx') AND (b.\"PARENTID\" = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.Where("a.\"CLICKS\" > 100 and a.\"ID\" = :id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"CLICKS\" > 100 and a.\"ID\" = :id)", sql); + query.ToList(); + } + [Fact] + public void WhereIf() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.WhereIf(true, a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"ID\" = 10)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE ((a.\"ID\" = 10 AND a.\"ID\" > 10 OR a.\"CLICKS\" > 100))", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"ID\" = 10) AND (a.\"CLICKS\" > 100)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" WHERE (a__Type.\"NAME\" = 'typeTitle')", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" WHERE (a__Type.\"NAME\" = 'typeTitle' AND a__Type.\"GUID\" = a.\"TYPEGUID\")", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a LEFT JOIN \"TESTTYPEINFO\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFO\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"NAME\" = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(true, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b, \"TESTTYPEPARENTINFO\" c WHERE (a.\"ID\" = 10 AND c.\"NAME\" = 'xxx') AND (b.\"PARENTID\" = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(true, "a.\"CLICKS\" > 100 and a.\"ID\" = :id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a WHERE (a.\"CLICKS\" > 100 and a.\"ID\" = :id)", sql); + query.ToList(); + + // ==========================================WhereIf(false) + + //����е�������a.Type��a.Type.Parent ���ǵ������� + query = select.WhereIf(false, a => a.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + query2 = select.From((s, b, c) => s + .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(false, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a, \"TESTTYPEINFO\" b, \"TESTTYPEPARENTINFO\" c", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(false, "a.\"CLICKS\" > 100 and a.\"ID\" = :id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22\" a", sql); + query.ToList(); + } + [Fact] + public void WhereExists() + { + var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); + + sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + + //.Offset(a.Id) + + .Any() + ).Any() + ).ToList(); + } + [Fact] + public void GroupBy() + { + var groupby = select.From((s, b, c) => s + .Where(a => a.Id == 1) + ) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()) + .Offset(10) + .Limit(2) + .ToList(a => new + { + a.Key.tt2, + cou1 = a.Count(), + arg1 = a.Avg(a.Key.mod4), + ccc2 = a.Key.tt2 ?? "now()", + //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") + ccc3 = a.Max(a.Value.Item3.Id) + }); + + var testpid1 = g.oracle.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); + g.oracle.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); + + var aggsql1 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist1 = select + .GroupBy(a => a.Title) + .ToList(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToSql(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToList(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql3 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid), + sum3 = b.Sum(b.Value.Type.Parent.Id) + }); + } + [Fact] + public void ToAggregate() + { + var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); + } + [Fact] + public void OrderBy() + { + var sql = select.Offset(10).OrderBy(a => new Random().NextDouble()).ToList(); + } + [Fact] + public void Skip_Offset() + { + var sql = select.Offset(10).ToList(); + } + [Fact] + public void Take_Limit() + { + var sql = select.Limit(10).ToList(); + } + [Fact] + public void Page() + { + var sql1 = select.Page(1, 10).ToList(); + var sql2 = select.Page(2, 10).ToList(); + var sql3 = select.Page(3, 10).ToList(); + + var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); + var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); + var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); + } + [Fact] + public void Distinct() + { + var t1 = select.Distinct().ToList(a => a.Title); + var t2 = select.Distinct().Limit(10).ToList(a => a.Title); + } + + [Fact] + public void Sum() + { + } + [Fact] + public void Min() + { + } + [Fact] + public void Max() + { + } + [Fact] + public void Avg() + { + } + [Fact] + public void As() + { + } + + [Fact] + public void AsTable() + { + + var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); + + Func tableRule = (type, oldname) => + { + if (type == typeof(Topic)) return oldname + "AsTable1"; + else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; + return oldname + "AsTable"; + }; + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\"", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx'", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" b ON b.\"GUID\" = a.\"TYPEGUID\"", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" b ON b.\"GUID\" = a.\"TYPEGUID\" AND b.\"NAME\" = 'xxx'", sql); + + query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" AND a__Type.\"NAME\" = 'xxx' LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\" WHERE (a__Type__Parent.\"ID\" = 10)", sql); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" a__Type__Parent ON a__Type__Parent.\"ID\" = a__Type.\"PARENTID\"", sql); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a__Type.\"GUID\", a__Type.\"PARENTID\", a__Type.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" a__Type ON a__Type.\"GUID\" = a.\"TYPEGUID\" LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" c ON c.\"ID\" = a__Type.\"PARENTID\"", sql); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", b.\"GUID\", b.\"PARENTID\", b.\"NAME\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFOAsTable2\" b ON a.\"TYPEGUID\" = b.\"GUID\" LEFT JOIN \"TESTTYPEPARENTINFOAsTable\" c ON b.\"PARENTID\" = c.\"ID\"", sql); + + //������϶����㲻�� + query = select.LeftJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\"", sql); + + query = select.LeftJoin("\"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", new { bname = "xxx" }).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"ID\", a.\"CLICKS\", a.\"TYPEGUID\", a.\"TITLE\", a.\"CREATETIME\" FROM \"TB_TOPIC22AsTable1\" a LEFT JOIN \"TESTTYPEINFO\" b on b.\"GUID\" = a.\"TYPEGUID\" and b.\"NAME\" = :bname", sql); + } + + public class TiOtmModel1 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public virtual TiOtmModel2 model2 { get; set; } + + public string m1name { get; set; } + } + public class TiOtmModel2 + { + [Column(IsPrimary = true)] + public int model2id { get; set; } + public virtual TiOtmModel1 model1 { get; set; } + + public string m2setting { get; set; } + + public List childs { get; set; } + } + public class TiOtmModel3 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model2111Idaaa { get; set; } + public string title { get; set; } + + public List childs2 { get; set; } + } + public class TiOtmModel4 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model3333Id333 { get; set; } + public string title444 { get; set; } + } + + [Fact] + public void Include_OneToMany() + { + var model1 = new TiOtmModel1 { m1name = DateTime.Now.Second.ToString() }; + model1.id = (int)g.oracle.Insert(model1).ExecuteIdentity(); + var model2 = new TiOtmModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; + g.oracle.Insert(model2).ExecuteAffrows(); + + var model3_1 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; + model3_1.id = (int)g.oracle.Insert(model3_1).ExecuteIdentity(); + var model3_2 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; + model3_2.id = (int)g.oracle.Insert(model3_2).ExecuteIdentity(); + var model3_3 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; + model3_3.id = (int)g.oracle.Insert(model3_2).ExecuteIdentity(); + + var model4s = new[] { + new TiOtmModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, + new TiOtmModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, + new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, + new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, + new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } + }; + Assert.Equal(5, g.oracle.Insert(model4s).ExecuteAffrows()); + + var t0 = g.oracle.Select() + .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t1 = g.oracle.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t2 = g.oracle.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + + var t00 = g.oracle.Select() + .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t11 = g.oracle.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t22 = g.oracle.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + } + + public class TiOtmModel11 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2id { get; set; } + public string m3setting { get; set; } + public TiOtmModel22 model2 { get; set; } + public string m1name { get; set; } + } + + public class TiOtmModel22 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public string m2setting { get; set; } + public List childs { get; set; } + } + public class TiOtmModel33 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2Id { get; set; } + public string title { get; set; } + public string setting { get; set; } + } + [Fact] + public void Include_OneToMany2() + { + string setting = "x"; + var model2 = new TiOtmModel22 { m2setting = DateTime.Now.Second.ToString() }; + model2.id = (int)g.oracle.Insert(model2).ExecuteIdentity(); + + var model3s = new[] + { + new TiOtmModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, + new TiOtmModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, + new TiOtmModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} + }; + Assert.Equal(3, g.oracle.Insert(model3s).ExecuteAffrows()); + + var model1 = new TiOtmModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; + model1.id = (int)g.oracle.Insert(model1).ExecuteIdentity(); + + var t1 = g.oracle.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + + var t11 = g.oracle.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + } + + [Fact] + public void Include_OneToChilds() + { + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_中国" + }; + tag1.Id = (int)g.oracle.Insert(tag1).ExecuteIdentity(); + var tag1_1 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_北京" + }; + tag1_1.Id = (int)g.oracle.Insert(tag1_1).ExecuteIdentity(); + var tag1_2 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_上海" + }; + tag1_2.Id = (int)g.oracle.Insert(tag1_2).ExecuteIdentity(); + + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_美国" + }; + tag2.Id = (int)g.oracle.Insert(tag2).ExecuteIdentity(); + var tag2_1 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_纽约" + }; + tag2_1.Id = (int)g.oracle.Insert(tag2_1).ExecuteIdentity(); + var tag2_2 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_华盛顿" + }; + tag2_2.Id = (int)g.oracle.Insert(tag2_2).ExecuteIdentity(); + + var tags0 = g.oracle.Select() + .Include(a => a.Parent) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags1 = g.oracle.Select() + .IncludeMany(a => a.Tags) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags2 = g.oracle.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags3 = g.oracle.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags11 = g.oracle.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags22 = g.oracle.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags33 = g.oracle.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + } + + [Fact] + public void Include_ManyToMany() + { + + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_01_中国" + }; + tag1.Id = (int)g.oracle.Insert(tag1).ExecuteIdentity(); + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_02_美国" + }; + tag2.Id = (int)g.oracle.Insert(tag2).ExecuteIdentity(); + var tag3 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_03_日本" + }; + tag3.Id = (int)g.oracle.Insert(tag3).ExecuteIdentity(); + + var song1 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_01_我是中国人.mp3", + Url = "http://ww.baidu.com/" + }; + song1.Id = (int)g.oracle.Insert(song1).ExecuteIdentity(); + var song2 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_02_爱你一万年.mp3", + Url = "http://ww.163.com/" + }; + song2.Id = (int)g.oracle.Insert(song2).ExecuteIdentity(); + var song3 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_03_千年等一回.mp3", + Url = "http://ww.sina.com/" + }; + song3.Id = (int)g.oracle.Insert(song3).ExecuteIdentity(); + + g.oracle.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.oracle.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.oracle.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.oracle.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.oracle.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.oracle.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); + + var songs1 = g.oracle.Select() + .IncludeMany(a => a.Tags) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs1.Count); + Assert.Equal(2, songs1[0].Tags.Count); + Assert.Equal(1, songs1[1].Tags.Count); + Assert.Equal(3, songs1[2].Tags.Count); + + var songs2 = g.oracle.Select() + .IncludeMany(a => a.Tags, + then => then.IncludeMany(t => t.Songs)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs2.Count); + Assert.Equal(2, songs2[0].Tags.Count); + Assert.Equal(1, songs2[1].Tags.Count); + Assert.Equal(3, songs2[2].Tags.Count); + + var tags3 = g.oracle.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + + + var songs11 = g.oracle.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs11.Count); + Assert.Equal(1, songs11[0].Tags.Count); + Assert.Equal(1, songs11[1].Tags.Count); + Assert.Equal(1, songs11[2].Tags.Count); + + var songs22 = g.oracle.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.IncludeMany(t => t.Songs.Take(1))) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs22.Count); + Assert.Equal(1, songs22[0].Tags.Count); + Assert.Equal(1, songs22[1].Tags.Count); + Assert.Equal(1, songs22[2].Tags.Count); + + var tags33 = g.oracle.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs.Take(1)) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleUpdateTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleUpdateTest.cs index 2fb79001..22f204aa 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleUpdateTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/Curd/OracleUpdateTest.cs @@ -3,125 +3,139 @@ using System; using System.Collections.Generic; using Xunit; -namespace FreeSql.Tests.Oracle { - public class OracleUpdateTest { - IUpdate update => g.oracle.Update(); +namespace FreeSql.Tests.Oracle +{ + public class OracleUpdateTest + { + IUpdate update => g.oracle.Update(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - - [Fact] - public void Dywhere() { - Assert.Null(g.oracle.Update().ToSql()); - Assert.Equal("UPDATE \"TB_TOPIC\" SET title='test' \r\nWHERE (\"ID\" = 1 OR \"ID\" = 2)", g.oracle.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); - Assert.Equal("UPDATE \"TB_TOPIC\" SET title='test1' \r\nWHERE (\"ID\" = 1)", g.oracle.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE \"TB_TOPIC\" SET title='test1' \r\nWHERE (\"ID\" = 1 OR \"ID\" = 2)", g.oracle.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE \"TB_TOPIC\" SET title='test1' \r\nWHERE (\"ID\" = 1)", g.oracle.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); - } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void SetSource() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = :p_0, \"TITLE\" = :p_1, \"CREATETIME\" = :p_2 WHERE (\"ID\" = 1)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(g.oracle.Update().ToSql()); + Assert.Equal("UPDATE \"TB_TOPIC\" SET title='test' \r\nWHERE (\"ID\" = 1 OR \"ID\" = 2)", g.oracle.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); + Assert.Equal("UPDATE \"TB_TOPIC\" SET title='test1' \r\nWHERE (\"ID\" = 1)", g.oracle.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE \"TB_TOPIC\" SET title='test1' \r\nWHERE (\"ID\" = 1 OR \"ID\" = 2)", g.oracle.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE \"TB_TOPIC\" SET title='test1' \r\nWHERE (\"ID\" = 1)", g.oracle.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); + } - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + [Fact] + public void SetSource() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = :p_0, \"TITLE\" = :p_1, \"CREATETIME\" = :p_2 WHERE (\"ID\" = 1)", sql); - sql = update.SetSource(items).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = CASE \"ID\" WHEN 1 THEN :p_0 WHEN 2 THEN :p_1 WHEN 3 THEN :p_2 WHEN 4 THEN :p_3 WHEN 5 THEN :p_4 WHEN 6 THEN :p_5 WHEN 7 THEN :p_6 WHEN 8 THEN :p_7 WHEN 9 THEN :p_8 WHEN 10 THEN :p_9 END, \"TITLE\" = CASE \"ID\" WHEN 1 THEN :p_10 WHEN 2 THEN :p_11 WHEN 3 THEN :p_12 WHEN 4 THEN :p_13 WHEN 5 THEN :p_14 WHEN 6 THEN :p_15 WHEN 7 THEN :p_16 WHEN 8 THEN :p_17 WHEN 9 THEN :p_18 WHEN 10 THEN :p_19 END, \"CREATETIME\" = CASE \"ID\" WHEN 1 THEN :p_20 WHEN 2 THEN :p_21 WHEN 3 THEN :p_22 WHEN 4 THEN :p_23 WHEN 5 THEN :p_24 WHEN 6 THEN :p_25 WHEN 7 THEN :p_26 WHEN 8 THEN :p_27 WHEN 9 THEN :p_28 WHEN 10 THEN :p_29 END WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = CASE \"ID\" WHEN 1 THEN :p_0 WHEN 2 THEN :p_1 WHEN 3 THEN :p_2 WHEN 4 THEN :p_3 WHEN 5 THEN :p_4 WHEN 6 THEN :p_5 WHEN 7 THEN :p_6 WHEN 8 THEN :p_7 WHEN 9 THEN :p_8 WHEN 10 THEN :p_9 END WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = CASE \"ID\" WHEN 1 THEN :p_0 WHEN 2 THEN :p_1 WHEN 3 THEN :p_2 WHEN 4 THEN :p_3 WHEN 5 THEN :p_4 WHEN 6 THEN :p_5 WHEN 7 THEN :p_6 WHEN 8 THEN :p_7 WHEN 9 THEN :p_8 WHEN 10 THEN :p_9 END, \"TITLE\" = CASE \"ID\" WHEN 1 THEN :p_10 WHEN 2 THEN :p_11 WHEN 3 THEN :p_12 WHEN 4 THEN :p_13 WHEN 5 THEN :p_14 WHEN 6 THEN :p_15 WHEN 7 THEN :p_16 WHEN 8 THEN :p_17 WHEN 9 THEN :p_18 WHEN 10 THEN :p_19 END, \"CREATETIME\" = CASE \"ID\" WHEN 1 THEN :p_20 WHEN 2 THEN :p_21 WHEN 3 THEN :p_22 WHEN 4 THEN :p_23 WHEN 5 THEN :p_24 WHEN 6 THEN :p_25 WHEN 7 THEN :p_26 WHEN 8 THEN :p_27 WHEN 9 THEN :p_28 WHEN 10 THEN :p_29 END WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020,1,1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CREATETIME\" = :p_0 WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void IgnoreColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = :p_0 WHERE (\"ID\" = 1)", sql); - } - [Fact] - public void UpdateColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = :p_0 WHERE (\"ID\" = 1)", sql); - } - [Fact] - public void Set() { - var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = :p_0 WHERE (\"ID\" = 1)", sql); + sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = CASE \"ID\" WHEN 1 THEN :p_0 WHEN 2 THEN :p_1 WHEN 3 THEN :p_2 WHEN 4 THEN :p_3 WHEN 5 THEN :p_4 WHEN 6 THEN :p_5 WHEN 7 THEN :p_6 WHEN 8 THEN :p_7 WHEN 9 THEN :p_8 WHEN 10 THEN :p_9 END WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = :p_0, \"CREATETIME\" = :p_1 WHERE (\"ID\" = 1)", sql); + sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CREATETIME\" = :p_0 WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void IgnoreColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = :p_0 WHERE (\"ID\" = 1)", sql); + } + [Fact] + public void UpdateColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = :p_0 WHERE (\"ID\" = 1)", sql); + } + [Fact] + public void Set() + { + var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = :p_0 WHERE (\"ID\" = 1)", sql); - sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = nvl(\"CLICKS\", 0) * 10 / 1 WHERE (\"ID\" = 1)", sql); + sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"TITLE\" = :p_0, \"CREATETIME\" = :p_1 WHERE (\"ID\" = 1)", sql); - sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"ID\" = (\"ID\" - 10) WHERE (\"ID\" = 1)", sql); + sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = nvl(\"CLICKS\", 0) * 10 / 1 WHERE (\"ID\" = 1)", sql); - int incrv = 10; - sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = nvl(\"CLICKS\", 0) * 10 / 1 WHERE (\"ID\" = 1)", sql); + sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"ID\" = (\"ID\" - 10) WHERE (\"ID\" = 1)", sql); - sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"ID\" = (\"ID\" - 10) WHERE (\"ID\" = 1)", sql); + int incrv = 10; + sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = nvl(\"CLICKS\", 0) * 10 / 1 WHERE (\"ID\" = 1)", sql); - sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = \"CLICKS\" * 10 / 1 WHERE (\"ID\" = 1)", sql); + sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"ID\" = (\"ID\" - 10) WHERE (\"ID\" = 1)", sql); - sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET \"ID\" = 10 WHERE (\"ID\" = 1)", sql); - } - [Fact] - public void SetRaw() { - var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + :incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET clicks = clicks + :incrClick WHERE (\"ID\" = 1)", sql); - } - [Fact] - public void Where() { - var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET title='newtitle' WHERE (\"ID\" = 1)", sql); + sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"CLICKS\" = \"CLICKS\" * 10 / 1 WHERE (\"ID\" = 1)", sql); - sql = update.Where("id = :id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET title='newtitle' WHERE (id = :id)", sql); + sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET \"ID\" = 10 WHERE (\"ID\" = 1)", sql); + } + [Fact] + public void SetRaw() + { + var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + :incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET clicks = clicks + :incrClick WHERE (\"ID\" = 1)", sql); + } + [Fact] + public void Where() + { + var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET title='newtitle' WHERE (\"ID\" = 1)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET title='newtitle' WHERE (\"ID\" = 1)", sql); + sql = update.Where("id = :id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET title='newtitle' WHERE (id = :id)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"TB_TOPIC\" SET title='newtitle' WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET title='newtitle' WHERE (\"ID\" = 1)", sql); - } - [Fact] - public void ExecuteAffrows() { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"TB_TOPIC\" SET title='newtitle' WHERE (\"ID\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteUpdated() { + } + [Fact] + public void ExecuteAffrows() + { - } + } + [Fact] + public void ExecuteUpdated() + { - [Fact] - public void AsTable() { - Assert.Null(g.oracle.Update().ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test' \r\nWHERE (\"ID\" = 1 OR \"ID\" = 2)", g.oracle.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"ID\" = 1)", g.oracle.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"ID\" = 1 OR \"ID\" = 2)", g.oracle.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"ID\" = 1)", g.oracle.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - } - } + } + + [Fact] + public void AsTable() + { + Assert.Null(g.oracle.Update().ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test' \r\nWHERE (\"ID\" = 1 OR \"ID\" = 2)", g.oracle.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"ID\" = 1)", g.oracle.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"ID\" = 1 OR \"ID\" = 2)", g.oracle.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"ID\" = 1)", g.oracle.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/BoolNullableTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/BoolNullableTest.cs index e5943264..d3da1a49 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/BoolNullableTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/BoolNullableTest.cs @@ -2,1561 +2,1595 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.OracleMapType { - public class BoolNullableTest { - class BoolNullableMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool))] - public bool? tobool { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool? tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool? tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool? toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool? toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool? toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool? tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool? tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool? tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool? tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool? tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool? toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool? toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool? touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool? touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool? toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool? toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool? tostring { get; set; } = true; - } - [Fact] - public void Bool() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item = new BoolNullableMap { tobool = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item = new BoolNullableMap { tobool = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update all - item.tobool = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item.tobool = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item.tobool = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item = new BoolNullableMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item = new BoolNullableMap { tosbyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item.tosbyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item.tosbytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item = new BoolNullableMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item = new BoolNullableMap { toshort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item.toshort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item.toshortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item = new BoolNullableMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item = new BoolNullableMap { toint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item.toint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item = new BoolNullableMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item = new BoolNullableMap { tointnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item.tointnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item = new BoolNullableMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item = new BoolNullableMap { tolong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item.tolong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item.tolongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item = new BoolNullableMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item = new BoolNullableMap { tobyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item.tobyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item.tobytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item = new BoolNullableMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item = new BoolNullableMap { toushort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item.toushort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item.toushortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item = new BoolNullableMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item = new BoolNullableMap { touint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item.touint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item = new BoolNullableMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item = new BoolNullableMap { touintnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item.touintnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item = new BoolNullableMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item = new BoolNullableMap { toulong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item.toulong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item.toulongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.oracle; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item = new BoolNullableMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item = new BoolNullableMap { tostring = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item.tostring = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.OracleMapType +{ + public class BoolNullableTest + { + class BoolNullableMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool))] + public bool? tobool { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool? tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool? tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool? toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool? toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool? toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool? tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool? tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool? tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool? tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool? tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool? toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool? toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool? touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool? touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool? toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool? toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool? tostring { get; set; } = true; + } + [Fact] + public void Bool() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item = new BoolNullableMap { tobool = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item = new BoolNullableMap { tobool = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update all + item.tobool = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item.tobool = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item.tobool = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item = new BoolNullableMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item = new BoolNullableMap { tosbyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item.tosbyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item.tosbytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item = new BoolNullableMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item = new BoolNullableMap { toshort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item.toshort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item.toshortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item = new BoolNullableMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item = new BoolNullableMap { toint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item.toint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item = new BoolNullableMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item = new BoolNullableMap { tointnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item.tointnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item = new BoolNullableMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item = new BoolNullableMap { tolong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item.tolong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item.tolongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item = new BoolNullableMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item = new BoolNullableMap { tobyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item.tobyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item.tobytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item = new BoolNullableMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item = new BoolNullableMap { toushort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item.toushort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item.toushortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item = new BoolNullableMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item = new BoolNullableMap { touint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item.touint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item = new BoolNullableMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item = new BoolNullableMap { touintnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item.touintnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item = new BoolNullableMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item = new BoolNullableMap { toulong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item.toulong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item.toulongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.oracle; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item = new BoolNullableMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item = new BoolNullableMap { tostring = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item.tostring = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/BoolTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/BoolTest.cs index b94db356..0aab5f9f 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/BoolTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/BoolTest.cs @@ -2,1095 +2,1129 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.OracleMapType { - public class BoolTest { - - class BoolMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool?))] - public bool toboolnullable { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool tostring { get; set; } = true; - } - - [Fact] - public void BoolNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item = new BoolMap { toboolnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update all - item.toboolnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item.toboolnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toboolnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toboolnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item = new BoolMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item = new BoolMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item = new BoolMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item = new BoolMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item = new BoolMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item = new BoolMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item = new BoolMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item = new BoolMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item = new BoolMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item = new BoolMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item = new BoolMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item = new BoolMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item = new BoolMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item = new BoolMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item = new BoolMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item = new BoolMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.oracle; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item = new BoolMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.OracleMapType +{ + public class BoolTest + { + + class BoolMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool?))] + public bool toboolnullable { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool tostring { get; set; } = true; + } + + [Fact] + public void BoolNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item = new BoolMap { toboolnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update all + item.toboolnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item.toboolnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toboolnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toboolnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item = new BoolMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item = new BoolMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item = new BoolMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item = new BoolMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item = new BoolMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item = new BoolMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item = new BoolMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item = new BoolMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item = new BoolMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item = new BoolMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item = new BoolMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item = new BoolMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item = new BoolMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item = new BoolMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item = new BoolMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item = new BoolMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.oracle; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item = new BoolMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/EnumTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/EnumTest.cs index eb87ac61..5665ab31 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/EnumTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/EnumTest.cs @@ -3,252 +3,259 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.OracleMapType { - public class EnumTest { - class EnumTestMap { - public Guid id { get; set; } +namespace FreeSql.Tests.OracleMapType +{ + public class EnumTest + { + class EnumTestMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(int))] - public ToStringMapEnum enum_to_int { get; set; } - [Column(MapType = typeof(int?))] - public ToStringMapEnum? enumnullable_to_int { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void EnumToString() { - //insert - var orm = g.oracle; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(int))] + public ToStringMapEnum enum_to_int { get; set; } + [Column(MapType = typeof(int?))] + public ToStringMapEnum? enumnullable_to_int { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void EnumToString() + { + //insert + var orm = g.oracle; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToString() { - //insert - var orm = g.oracle; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToString() + { + //insert + var orm = g.oracle; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void EnumToInt() { - //insert - var orm = g.oracle; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + [Fact] + public void EnumToInt() + { + //insert + var orm = g.oracle; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //update all - item.enum_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update all + item.enum_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - item.enum_to_int = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + item.enum_to_int = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToInt() { - //insert - var orm = g.oracle; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToInt() + { + //insert + var orm = g.oracle; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); + item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); - //update all - item.enumnullable_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); + //update all + item.enumnullable_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); - item.enumnullable_to_int = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + item.enumnullable_to_int = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/ToStringTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/ToStringTest.cs index 261d8746..5b5c8540 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/ToStringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/MapType/ToStringTest.cs @@ -3,555 +3,568 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.OracleMapType { - public class ToStringTest { - class ToStringMap { - public Guid id { get; set; } +namespace FreeSql.Tests.OracleMapType +{ + public class ToStringTest + { + class ToStringMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan timespan_to_string { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan? timespannullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan timespan_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan? timespannullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime datetime_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime? datetimenullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime datetime_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime? datetimenullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid guid_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid? guidnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid guid_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid? guidnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger biginteger_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger? bigintegernullable_to_string { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void Enum1() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(string))] + public BigInteger biginteger_to_string { get; set; } + [Column(MapType = typeof(string))] + public BigInteger? bigintegernullable_to_string { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void Enum1() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullable() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullable() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigInteger1() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(0, find.biginteger_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigInteger1() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(0, find.biginteger_to_string); - item = new ToStringMap { biginteger_to_string = 100 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(100, find.biginteger_to_string); + item = new ToStringMap { biginteger_to_string = 100 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(100, find.biginteger_to_string); - //update all - item.biginteger_to_string = 200; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(200, find.biginteger_to_string); + //update all + item.biginteger_to_string = 200; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(200, find.biginteger_to_string); - item.biginteger_to_string = 205; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(205, find.biginteger_to_string); + item.biginteger_to_string = 205; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(205, find.biginteger_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(522, find.biginteger_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(522, find.biginteger_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(10005, find.biginteger_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(10005, find.biginteger_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigIntegerNullable() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigIntegerNullable() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - item = new ToStringMap { bigintegernullable_to_string = 101 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(101, find.bigintegernullable_to_string); + item = new ToStringMap { bigintegernullable_to_string = 101 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(101, find.bigintegernullable_to_string); - //update all - item.bigintegernullable_to_string = 2004; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(2004, find.bigintegernullable_to_string); + //update all + item.bigintegernullable_to_string = 2004; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(2004, find.bigintegernullable_to_string); - item.bigintegernullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + item.bigintegernullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(998, find.bigintegernullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(998, find.bigintegernullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.bigintegernullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.bigintegernullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpan1() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.Zero, find.timespan_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpan1() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.Zero, find.timespan_to_string); - item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); + item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); - //update all - item.timespan_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); + //update all + item.timespan_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpanNullable() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpanNullable() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); + item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); - //update all - item.timespannullable_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); + //update all + item.timespannullable_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); - item.timespannullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + item.timespannullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.timespannullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.timespannullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTime1() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.MinValue, find.datetime_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTime1() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.MinValue, find.datetime_to_string); - item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); + item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); - //update all - item.datetime_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); + //update all + item.datetime_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTimeNullable() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTimeNullable() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); + item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); - //update all - item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); + //update all + item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); - item.datetimenullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + item.datetimenullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.datetimenullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.datetimenullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void Guid1() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(Guid.Empty, find.guid_to_string); + [Fact] + public void Guid1() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(Guid.Empty, find.guid_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guid_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guid_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update all - newid = Guid.NewGuid(); - item.guid_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + //update all + newid = Guid.NewGuid(); + item.guid_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guid_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guid_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void GuidNullable() { - //insert - var orm = g.oracle; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void GuidNullable() + { + //insert + var orm = g.oracle; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guidnullable_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guidnullable_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - //update all - newid = Guid.NewGuid(); - item.guidnullable_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + //update all + newid = Guid.NewGuid(); + item.guidnullable_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - item.guidnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + item.guidnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guidnullable_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guidnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.guidnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.guidnullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleAdo/OracleAdoTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleAdo/OracleAdoTest.cs index 3fd79377..a2c24d8e 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleAdo/OracleAdoTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleAdo/OracleAdoTest.cs @@ -2,54 +2,65 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.Oracle { - public class OracleAdoTest { - [Fact] - public void Pool() { - var t1 = g.oracle.Ado.MasterPool.StatisticsFullily; - } +namespace FreeSql.Tests.Oracle +{ + public class OracleAdoTest + { + [Fact] + public void Pool() + { + var t1 = g.oracle.Ado.MasterPool.StatisticsFullily; + } - [Fact] - public void SlavePools() { - var t2 = g.oracle.Ado.SlavePools.Count; - } + [Fact] + public void SlavePools() + { + var t2 = g.oracle.Ado.SlavePools.Count; + } - [Fact] - public void ExecuteReader() { - - } - [Fact] - public void ExecuteArray() { - - } - [Fact] - public void ExecuteNonQuery() { - - } - [Fact] - public void ExecuteScalar() { - - } + [Fact] + public void ExecuteReader() + { - [Fact] - public void Query() { + } + [Fact] + public void ExecuteArray() + { - var t3 = g.oracle.Ado.Query("select * from \"TB_TOPIC\""); + } + [Fact] + public void ExecuteNonQuery() + { - var t4 = g.oracle.Ado.Query<(int, string, string)>("select * from \"TB_TOPIC\""); + } + [Fact] + public void ExecuteScalar() + { - var t5 = g.oracle.Ado.Query("select * from \"TB_TOPIC\""); - } + } - [Fact] - public void QueryMultipline() { - //var t3 = g.oracle.Ado.Query("select * from \"TB_TOPIC\"; select * from \"TB_TOPIC\"; select * from \"TB_TOPIC\""); - } + [Fact] + public void Query() + { - class xxx { - public int Id { get; set; } - public string Path { get; set; } - public string Title2 { get; set; } - } - } + var t3 = g.oracle.Ado.Query("select * from \"TB_TOPIC\""); + + var t4 = g.oracle.Ado.Query<(int, string, string)>("select * from \"TB_TOPIC\""); + + var t5 = g.oracle.Ado.Query("select * from \"TB_TOPIC\""); + } + + [Fact] + public void QueryMultipline() + { + //var t3 = g.oracle.Ado.Query("select * from \"TB_TOPIC\"; select * from \"TB_TOPIC\"; select * from \"TB_TOPIC\""); + } + + class xxx + { + public int Id { get; set; } + public string Path { get; set; } + public string Title2 { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleCodeFirstTest.cs index 32b94b6f..9dcd8f9d 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleCodeFirstTest.cs @@ -6,81 +6,92 @@ using System.Linq; using System.Text; using Xunit; -namespace FreeSql.Tests.Oracle { - public class OracleCodeFirstTest { +namespace FreeSql.Tests.Oracle +{ + public class OracleCodeFirstTest + { - [Fact] - public void ı_ֶ() { - var sql = g.oracle.CodeFirst.GetComparisonDDLStatements<ı>(); - g.oracle.CodeFirst.SyncStructure<ı>(); + [Fact] + public void ı_ֶ() + { + var sql = g.oracle.CodeFirst.GetComparisonDDLStatements<ı>(); + g.oracle.CodeFirst.SyncStructure<ı>(); - var item = new ı { - = "Ա", - ʱ = DateTime.Now - }; - Assert.Equal(1, g.oracle.Insert<ı>().AppendData(item).ExecuteAffrows()); - Assert.NotEqual(Guid.Empty, item.); - var item2 = g.oracle.Select<ı>().Where(a => a. == item.).First(); - Assert.NotNull(item2); - Assert.Equal(item., item2.); - Assert.Equal(item., item2.); - } - class ı { - [Column(IsPrimary = true)] - public Guid { get; set; } + var item = new ı + { + = "Ա", + ʱ = DateTime.Now + }; + Assert.Equal(1, g.oracle.Insert<ı>().AppendData(item).ExecuteAffrows()); + Assert.NotEqual(Guid.Empty, item.); + var item2 = g.oracle.Select<ı>().Where(a => a. == item.).First(); + Assert.NotNull(item2); + Assert.Equal(item., item2.); + Assert.Equal(item., item2.); + } + class ı + { + [Column(IsPrimary = true)] + public Guid { get; set; } - public string { get; set; } + public string { get; set; } - public DateTime ʱ { get; set; } - } + public DateTime ʱ { get; set; } + } - [Fact] - public void AddUniques() { - var sql = g.oracle.CodeFirst.GetComparisonDDLStatements(); - g.oracle.CodeFirst.SyncStructure(); - } - [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] - class AddUniquesInfo { - public Guid id { get; set; } - [Column(Unique = "uk_phone")] - public string phone { get; set; } + [Fact] + public void AddUniques() + { + var sql = g.oracle.CodeFirst.GetComparisonDDLStatements(); + g.oracle.CodeFirst.SyncStructure(); + } + [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] + class AddUniquesInfo + { + public Guid id { get; set; } + [Column(Unique = "uk_phone")] + public string phone { get; set; } - [Column(Unique = "uk_group_index, uk_group_index22")] - public string group { get; set; } - [Column(Unique = "uk_group_index")] - public int index { get; set; } - [Column(Unique = "uk_group_index22")] - public string index22 { get; set; } - } - [Fact] - public void AddField() { - var sql = g.oracle.CodeFirst.GetComparisonDDLStatements(); + [Column(Unique = "uk_group_index, uk_group_index22")] + public string group { get; set; } + [Column(Unique = "uk_group_index")] + public int index { get; set; } + [Column(Unique = "uk_group_index22")] + public string index22 { get; set; } + } + [Fact] + public void AddField() + { + var sql = g.oracle.CodeFirst.GetComparisonDDLStatements(); - var id = g.oracle.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); + var id = g.oracle.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); - //var inserted = g.oracle.Insert().AppendData(new TopicAddField { }).ExecuteInserted(); - } + //var inserted = g.oracle.Insert().AppendData(new TopicAddField { }).ExecuteInserted(); + } - [Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")] - public class TopicAddField { - [Column(IsIdentity = true)] - public int Id { get; set; } + [Table(Name = "TopicAddField", OldName = "xxxtb.TopicAddField")] + public class TopicAddField + { + [Column(IsIdentity = true)] + public int Id { get; set; } - public string name { get; set; } + public string name { get; set; } - [Column(DbType = "varchar2(200 char) not null", OldName = "title")] - public string title2 { get; set; } = "10"; + [Column(DbType = "varchar2(200 char) not null", OldName = "title")] + public string title2 { get; set; } = "10"; - [Column(IsIgnore = true)] - public DateTime ct { get; set; } = DateTime.Now; - } + [Column(IsIgnore = true)] + public DateTime ct { get; set; } = DateTime.Now; + } - [Fact] - public void GetComparisonDDLStatements() { + [Fact] + public void GetComparisonDDLStatements() + { - var sql = g.oracle.CodeFirst.GetComparisonDDLStatements(); - if (string.IsNullOrEmpty(sql) == false) { - Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` ( + var sql = g.oracle.CodeFirst.GetComparisonDDLStatements(); + if (string.IsNullOrEmpty(sql) == false) + { + Assert.Equal(@"CREATE TABLE IF NOT EXISTS `cccddd`.`tb_alltype` ( `Id` INT(11) NOT NULL AUTO_INCREMENT, `Bool` BIT(1) NOT NULL, `SByte` TINYINT(3) NOT NULL, @@ -127,114 +138,117 @@ namespace FreeSql.Tests.Oracle { PRIMARY KEY (`Id`) ) Engine=InnoDB; ", sql); - } + } - //sql = g.oracle.CodeFirst.GetComparisonDDLStatements(); - } + //sql = g.oracle.CodeFirst.GetComparisonDDLStatements(); + } - IInsert insert => g.oracle.Insert(); - ISelect select => g.oracle.Select(); + IInsert insert => g.oracle.Insert(); + ISelect select => g.oracle.Select(); - [Fact] - public void CurdAllField() { - var item = new TableAllType { }; - item.Id = (int)insert.AppendData(item).ExecuteIdentity(); + [Fact] + public void CurdAllField() + { + var item = new TableAllType { }; + item.Id = (int)insert.AppendData(item).ExecuteIdentity(); - var newitem = select.Where(a => a.Id == item.Id).ToOne(); + var newitem = select.Where(a => a.Id == item.Id).ToOne(); - var item2 = new TableAllType { - Bool = true, - BoolNullable = true, - Byte = 255, - ByteNullable = 127, - Bytes = Encoding.UTF8.GetBytes("й"), - DateTime = DateTime.Now, - DateTimeNullable = DateTime.Now.AddHours(-1), - Decimal = 99.99M, - DecimalNullable = 99.98M, - Double = 999.99, - DoubleNullable = 999.98, - Enum1 = TableAllTypeEnumType1.e5, - Enum1Nullable = TableAllTypeEnumType1.e3, - Enum2 = TableAllTypeEnumType2.f2, - Enum2Nullable = TableAllTypeEnumType2.f3, - Float = 19.99F, - FloatNullable = 19.98F, - Guid = Guid.NewGuid(), - GuidNullable = Guid.NewGuid(), - Int = int.MaxValue, - IntNullable = int.MinValue, - SByte = 100, - SByteNullable = 99, - Short = short.MaxValue, - ShortNullable = short.MinValue, - String = "йstring", - TimeSpan = TimeSpan.FromSeconds(999), - TimeSpanNullable = TimeSpan.FromSeconds(60), - UInt = uint.MaxValue, - UIntNullable = uint.MinValue, - ULong = ulong.MaxValue, - ULongNullable = ulong.MinValue, - UShort = ushort.MaxValue, - UShortNullable = ushort.MinValue, - testFielLongNullable = long.MinValue - }; - item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); - var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); + var item2 = new TableAllType + { + Bool = true, + BoolNullable = true, + Byte = 255, + ByteNullable = 127, + Bytes = Encoding.UTF8.GetBytes("й"), + DateTime = DateTime.Now, + DateTimeNullable = DateTime.Now.AddHours(-1), + Decimal = 99.99M, + DecimalNullable = 99.98M, + Double = 999.99, + DoubleNullable = 999.98, + Enum1 = TableAllTypeEnumType1.e5, + Enum1Nullable = TableAllTypeEnumType1.e3, + Enum2 = TableAllTypeEnumType2.f2, + Enum2Nullable = TableAllTypeEnumType2.f3, + Float = 19.99F, + FloatNullable = 19.98F, + Guid = Guid.NewGuid(), + GuidNullable = Guid.NewGuid(), + Int = int.MaxValue, + IntNullable = int.MinValue, + SByte = 100, + SByteNullable = 99, + Short = short.MaxValue, + ShortNullable = short.MinValue, + String = "йstring", + TimeSpan = TimeSpan.FromSeconds(999), + TimeSpanNullable = TimeSpan.FromSeconds(60), + UInt = uint.MaxValue, + UIntNullable = uint.MinValue, + ULong = ulong.MaxValue, + ULongNullable = ulong.MinValue, + UShort = ushort.MaxValue, + UShortNullable = ushort.MinValue, + testFielLongNullable = long.MinValue + }; + item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); + var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); - var items = select.ToList(); - } + var items = select.ToList(); + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - public string id2 { get; set; } = "id2=10"; + public string id2 { get; set; } = "id2=10"; - public bool Bool { get; set; } - public sbyte SByte { get; set; } - public short Short { get; set; } - public int Int { get; set; } - public long Long { get; set; } - public byte Byte { get; set; } - public ushort UShort { get; set; } - public uint UInt { get; set; } - public ulong ULong { get; set; } - public double Double { get; set; } - public float Float { get; set; } - public decimal Decimal { get; set; } - public TimeSpan TimeSpan { get; set; } - public DateTime DateTime { get; set; } - public DateTime DateTimeOffSet { get; set; } - public byte[] Bytes { get; set; } - public string String { get; set; } - public Guid Guid { get; set; } + public bool Bool { get; set; } + public sbyte SByte { get; set; } + public short Short { get; set; } + public int Int { get; set; } + public long Long { get; set; } + public byte Byte { get; set; } + public ushort UShort { get; set; } + public uint UInt { get; set; } + public ulong ULong { get; set; } + public double Double { get; set; } + public float Float { get; set; } + public decimal Decimal { get; set; } + public TimeSpan TimeSpan { get; set; } + public DateTime DateTime { get; set; } + public DateTime DateTimeOffSet { get; set; } + public byte[] Bytes { get; set; } + public string String { get; set; } + public Guid Guid { get; set; } - public bool? BoolNullable { get; set; } - public sbyte? SByteNullable { get; set; } - public short? ShortNullable { get; set; } - public int? IntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? ByteNullable { get; set; } - public ushort? UShortNullable { get; set; } - public uint? UIntNullable { get; set; } - public ulong? ULongNullable { get; set; } - public double? DoubleNullable { get; set; } - public float? FloatNullable { get; set; } - public decimal? DecimalNullable { get; set; } - public TimeSpan? TimeSpanNullable { get; set; } - public DateTime? DateTimeNullable { get; set; } - public DateTime? DateTimeOffSetNullable { get; set; } - public Guid? GuidNullable { get; set; } + public bool? BoolNullable { get; set; } + public sbyte? SByteNullable { get; set; } + public short? ShortNullable { get; set; } + public int? IntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? ByteNullable { get; set; } + public ushort? UShortNullable { get; set; } + public uint? UIntNullable { get; set; } + public ulong? ULongNullable { get; set; } + public double? DoubleNullable { get; set; } + public float? FloatNullable { get; set; } + public decimal? DecimalNullable { get; set; } + public TimeSpan? TimeSpanNullable { get; set; } + public DateTime? DateTimeNullable { get; set; } + public DateTime? DateTimeOffSetNullable { get; set; } + public Guid? GuidNullable { get; set; } - public TableAllTypeEnumType1 Enum1 { get; set; } - public TableAllTypeEnumType1? Enum1Nullable { get; set; } - public TableAllTypeEnumType2 Enum2 { get; set; } - public TableAllTypeEnumType2? Enum2Nullable { get; set; } - } + public TableAllTypeEnumType1 Enum1 { get; set; } + public TableAllTypeEnumType1? Enum1Nullable { get; set; } + public TableAllTypeEnumType2 Enum2 { get; set; } + public TableAllTypeEnumType2? Enum2Nullable { get; set; } + } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleDbFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleDbFirstTest.cs index 639e37ee..841ef36b 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleDbFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleDbFirstTest.cs @@ -2,20 +2,24 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.Oracle { - public class OracleDbFirstTest { - [Fact] - public void GetDatabases() { +namespace FreeSql.Tests.Oracle +{ + public class OracleDbFirstTest + { + [Fact] + public void GetDatabases() + { - var t1 = g.oracle.DbFirst.GetDatabases(); + var t1 = g.oracle.DbFirst.GetDatabases(); - } + } - [Fact] - public void GetTablesByDatabase() { + [Fact] + public void GetTablesByDatabase() + { - var t2 = g.oracle.DbFirst.GetTablesByDatabase(); + var t2 = g.oracle.DbFirst.GetTablesByDatabase(); - } - } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/ConvertTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/ConvertTest.cs index e01de2fe..af5cc3f0 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/ConvertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/ConvertTest.cs @@ -4,143 +4,166 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.OracleExpression { - public class ConvertTest { +namespace FreeSql.Tests.OracleExpression +{ + public class ConvertTest + { - ISelect select => g.oracle.Select(); + ISelect select => g.oracle.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void ToBoolean() { - var data = new List(); - //data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); - //data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); - } - [Fact] - public void ToByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); - data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); - } - [Fact] - public void ToChar() { - var data = new List(); - data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); - data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); - } - [Fact] - public void ToDateTime() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); - } - [Fact] - public void ToDecimal() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToDouble() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt32() { - var data = new List(); - data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); - data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToSByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); - data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); - } - [Fact] - public void ToSingle() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); - data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); - } - [Fact] - public void ToUInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt32() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); - } + [Fact] + public void ToBoolean() + { + var data = new List(); + //data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); + //data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); + } + [Fact] + public void ToByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); + data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); + } + [Fact] + public void ToChar() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); + data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); + } + [Fact] + public void ToDateTime() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); + } + [Fact] + public void ToDecimal() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToDouble() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt32() + { + var data = new List(); + data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); + data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToSByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); + data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); + } + [Fact] + public void ToSingle() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); + data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); + } + [Fact] + public void ToUInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt32() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); + } - [Fact] - public void Guid_Parse() { - var data = new List(); - data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); - } + [Fact] + public void Guid_Parse() + { + var data = new List(); + data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); + } - [Fact] - public void Guid_NewGuid() { - var data = new List(); - //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); - } + [Fact] + public void Guid_NewGuid() + { + var data = new List(); + //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); + } - [Fact] - public void Random() { - var data = new List(); - data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); - data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); - } - } + [Fact] + public void Random() + { + var data = new List(); + data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); + data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/DateTimeTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/DateTimeTest.cs index 48bedc9e..0fe69d3a 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/DateTimeTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/DateTimeTest.cs @@ -4,664 +4,703 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.OracleExpression { - public class DateTimeTest { - - ISelect select => g.oracle.Select(); - - [Table(Name = "tb_topic111333")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - [Table(Name = "TestTypeInfo333")] - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - public DateTime Time { get; set; } - } - [Table(Name = "TestTypeParentInf1")] - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - public DateTime Time2 { get; set; } - } - [Fact] - public void Now() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void UtcNow() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void Date() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) - } - [Fact] - public void TimeOfDay() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) - } - [Fact] - public void DayOfWeek() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) - } - [Fact] - public void Day() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) - } - [Fact] - public void DayOfYear() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) - } - [Fact] - public void Month() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (month(a.`CreateTime`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (month(a__Type.`Time`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (month(a__Type__Parent.`Time2`) > month(now())) - } - [Fact] - public void Year() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (year(a.`CreateTime`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (year(a__Type.`Time`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (year(a__Type__Parent.`Time2`) > year(now())) - } - [Fact] - public void Hour() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (hour(a.`CreateTime`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (hour(a__Type.`Time`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) - } - [Fact] - public void Minute() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (minute(a.`CreateTime`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (minute(a__Type.`Time`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) - } - [Fact] - public void Second() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (second(a.`CreateTime`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (second(a__Type.`Time`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (second(a__Type__Parent.`Time2`) > second(now())) - } - [Fact] - public void Millisecond() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) - } - [Fact] - public void AddDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) - } - [Fact] - public void AddHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) - } - [Fact] - public void AddMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) - } - [Fact] - public void AddMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) - } - [Fact] - public void AddMonths() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) - } - [Fact] - public void AddSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) - } - [Fact] - public void AddTicks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) - } - [Fact] - public void AddYears() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a."TITLE", a."CREATETIME" - //FROM "TB_TOPIC111333" a - //WHERE ((extract(day from (systimestamp-a."CREATETIME"))*86400+extract(hour from (systimestamp-a."CREATETIME"))*3600+extract(minute from (systimestamp-a."CREATETIME"))*60+extract(second from (systimestamp-a."CREATETIME"))) > 0) - - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" - //FROM "TB_TOPIC111333" a - //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" - //WHERE ((extract(day from (systimestamp-a__Type."TIME"))*86400+extract(hour from (systimestamp-a__Type."TIME"))*3600+extract(minute from (systimestamp-a__Type."TIME"))*60+extract(second from (systimestamp-a__Type."TIME"))) > 0) - - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" - //FROM "TB_TOPIC111333" a - //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" - //LEFT JOIN "TESTTYPEPARENTINF1" a__Type__Parent ON a__Type__Parent."ID" = a__Type."PARENTID" - //WHERE ((extract(day from (systimestamp-a__Type__Parent."TIME2"))*86400+extract(hour from (systimestamp-a__Type__Parent."TIME2"))*3600+extract(minute from (systimestamp-a__Type__Parent."TIME2"))*60+extract(second from (systimestamp-a__Type__Parent."TIME2"))) > 0) - data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a."TITLE", a."CREATETIME" - //FROM "TB_TOPIC111333" a - //WHERE ((a."CREATETIME"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" - - //FROM "TB_TOPIC111333" a - //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" - //WHERE ((a__Type."TIME"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" - - //FROM "TB_TOPIC111333" a - //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" - //LEFT JOIN "TESTTYPEPARENTINF1" a__Type__Parent ON a__Type__Parent."ID" = a__Type."PARENTID" - //WHERE ((a__Type__Parent."TIME2"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") - } - [Fact] - public void _ЧͬSubtract() { - var data = new List(); - data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a."TITLE", a."CREATETIME" - //FROM "TB_TOPIC111333" a - //WHERE ((extract(day from (systimestamp-a."CREATETIME"))*86400+extract(hour from (systimestamp-a."CREATETIME"))*3600+extract(minute from (systimestamp-a."CREATETIME"))*60+extract(second from (systimestamp-a."CREATETIME"))) > 0) - - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" - //FROM "TB_TOPIC111333" a - //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" - //WHERE ((extract(day from (systimestamp-a__Type."TIME"))*86400+extract(hour from (systimestamp-a__Type."TIME"))*3600+extract(minute from (systimestamp-a__Type."TIME"))*60+extract(second from (systimestamp-a__Type."TIME"))) > 0) - - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" - //FROM "TB_TOPIC111333" a - //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" - //LEFT JOIN "TESTTYPEPARENTINF1" a__Type__Parent ON a__Type__Parent."ID" = a__Type."PARENTID" - //WHERE ((extract(day from (systimestamp-a__Type__Parent."TIME2"))*86400+extract(hour from (systimestamp-a__Type__Parent."TIME2"))*3600+extract(minute from (systimestamp-a__Type__Parent."TIME2"))*60+extract(second from (systimestamp-a__Type__Parent."TIME2"))) > 0) - data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a."TITLE", a."CREATETIME" - //FROM "TB_TOPIC111333" a - //WHERE ((a."CREATETIME"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" - - //FROM "TB_TOPIC111333" a - //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" - //WHERE ((a__Type."TIME"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") - //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" - - //FROM "TB_TOPIC111333" a - //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" - //LEFT JOIN "TESTTYPEPARENTINF1" a__Type__Parent ON a__Type__Parent."ID" = a__Type."PARENTID" - //WHERE ((a__Type__Parent."TIME2"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) - } - - [Fact] - public void DateTime_Compare() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((a.`CreateTime`) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) - } - [Fact] - public void DateTime_DaysInMonth() { - var data = new List(); - data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) - } - [Fact] - public void DateTime_Equals() { - var data = new List(); - data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void DateTime_IsLeapYear() { - var data = new List(); - data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) - } - [Fact] - public void DateTime_Parse() { - var data = new List(); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) - } - } +namespace FreeSql.Tests.OracleExpression +{ + public class DateTimeTest + { + + ISelect select => g.oracle.Select(); + + [Table(Name = "tb_topic111333")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + [Table(Name = "TestTypeInfo333")] + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + public DateTime Time { get; set; } + } + [Table(Name = "TestTypeParentInf1")] + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + public DateTime Time2 { get; set; } + } + [Fact] + public void Now() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void UtcNow() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void Date() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) + } + [Fact] + public void TimeOfDay() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) + } + [Fact] + public void DayOfWeek() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) + } + [Fact] + public void Day() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) + } + [Fact] + public void DayOfYear() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) + } + [Fact] + public void Month() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (month(a.`CreateTime`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (month(a__Type.`Time`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (month(a__Type__Parent.`Time2`) > month(now())) + } + [Fact] + public void Year() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (year(a.`CreateTime`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (year(a__Type.`Time`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (year(a__Type__Parent.`Time2`) > year(now())) + } + [Fact] + public void Hour() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (hour(a.`CreateTime`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (hour(a__Type.`Time`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) + } + [Fact] + public void Minute() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (minute(a.`CreateTime`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (minute(a__Type.`Time`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) + } + [Fact] + public void Second() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (second(a.`CreateTime`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (second(a__Type.`Time`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (second(a__Type__Parent.`Time2`) > second(now())) + } + [Fact] + public void Millisecond() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) + } + [Fact] + public void AddDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) + } + [Fact] + public void AddHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) + } + [Fact] + public void AddMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) + } + [Fact] + public void AddMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) + } + [Fact] + public void AddMonths() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) + } + [Fact] + public void AddSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) + } + [Fact] + public void AddTicks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) + } + [Fact] + public void AddYears() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a."TITLE", a."CREATETIME" + //FROM "TB_TOPIC111333" a + //WHERE ((extract(day from (systimestamp-a."CREATETIME"))*86400+extract(hour from (systimestamp-a."CREATETIME"))*3600+extract(minute from (systimestamp-a."CREATETIME"))*60+extract(second from (systimestamp-a."CREATETIME"))) > 0) + + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" + //FROM "TB_TOPIC111333" a + //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" + //WHERE ((extract(day from (systimestamp-a__Type."TIME"))*86400+extract(hour from (systimestamp-a__Type."TIME"))*3600+extract(minute from (systimestamp-a__Type."TIME"))*60+extract(second from (systimestamp-a__Type."TIME"))) > 0) + + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" + //FROM "TB_TOPIC111333" a + //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" + //LEFT JOIN "TESTTYPEPARENTINF1" a__Type__Parent ON a__Type__Parent."ID" = a__Type."PARENTID" + //WHERE ((extract(day from (systimestamp-a__Type__Parent."TIME2"))*86400+extract(hour from (systimestamp-a__Type__Parent."TIME2"))*3600+extract(minute from (systimestamp-a__Type__Parent."TIME2"))*60+extract(second from (systimestamp-a__Type__Parent."TIME2"))) > 0) + data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a."TITLE", a."CREATETIME" + //FROM "TB_TOPIC111333" a + //WHERE ((a."CREATETIME"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" + + //FROM "TB_TOPIC111333" a + //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" + //WHERE ((a__Type."TIME"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" + + //FROM "TB_TOPIC111333" a + //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" + //LEFT JOIN "TESTTYPEPARENTINF1" a__Type__Parent ON a__Type__Parent."ID" = a__Type."PARENTID" + //WHERE ((a__Type__Parent."TIME2"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") + } + [Fact] + public void _ЧͬSubtract() + { + var data = new List(); + data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a."TITLE", a."CREATETIME" + //FROM "TB_TOPIC111333" a + //WHERE ((extract(day from (systimestamp-a."CREATETIME"))*86400+extract(hour from (systimestamp-a."CREATETIME"))*3600+extract(minute from (systimestamp-a."CREATETIME"))*60+extract(second from (systimestamp-a."CREATETIME"))) > 0) + + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" + //FROM "TB_TOPIC111333" a + //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" + //WHERE ((extract(day from (systimestamp-a__Type."TIME"))*86400+extract(hour from (systimestamp-a__Type."TIME"))*3600+extract(minute from (systimestamp-a__Type."TIME"))*60+extract(second from (systimestamp-a__Type."TIME"))) > 0) + + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" + //FROM "TB_TOPIC111333" a + //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" + //LEFT JOIN "TESTTYPEPARENTINF1" a__Type__Parent ON a__Type__Parent."ID" = a__Type."PARENTID" + //WHERE ((extract(day from (systimestamp-a__Type__Parent."TIME2"))*86400+extract(hour from (systimestamp-a__Type__Parent."TIME2"))*3600+extract(minute from (systimestamp-a__Type__Parent."TIME2"))*60+extract(second from (systimestamp-a__Type__Parent."TIME2"))) > 0) + data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a."TITLE", a."CREATETIME" + //FROM "TB_TOPIC111333" a + //WHERE ((a."CREATETIME"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" + + //FROM "TB_TOPIC111333" a + //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" + //WHERE ((a__Type."TIME"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") + //SELECT a."ID", a."CLICKS", a."TYPEGUID", a__Type."GUID", a__Type."PARENTID", a__Type."NAME", a__Type."TIME", a."TITLE", a."CREATETIME" + + //FROM "TB_TOPIC111333" a + //LEFT JOIN "TESTTYPEINFO333" a__Type ON a__Type."GUID" = a."TYPEGUID" + //LEFT JOIN "TESTTYPEPARENTINF1" a__Type__Parent ON a__Type__Parent."ID" = a__Type."PARENTID" + //WHERE ((a__Type__Parent."TIME2"-numtodsinterval((1)*86400,'second')) > a."CREATETIME") + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) + } + + [Fact] + public void DateTime_Compare() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((a.`CreateTime`) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) + } + [Fact] + public void DateTime_DaysInMonth() + { + var data = new List(); + data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) + } + [Fact] + public void DateTime_Equals() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void DateTime_IsLeapYear() + { + var data = new List(); + data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) + } + [Fact] + public void DateTime_Parse() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/MathTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/MathTest.cs index 51bd9fb1..ca9156ca 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/MathTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/MathTest.cs @@ -4,129 +4,153 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.OracleExpression { - public class MathTest { +namespace FreeSql.Tests.OracleExpression +{ + public class MathTest + { - ISelect select => g.oracle.Select(); + ISelect select => g.oracle.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void PI() { - var data = new List(); - data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); - } - [Fact] - public void Abs() { - var data = new List(); - data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Sign() { - var data = new List(); - data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Floor() { - var data = new List(); - data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); - } - [Fact] - public void Ceiling() { - var data = new List(); - data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Round() { - var data = new List(); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); - } - [Fact] - public void Exp() { - var data = new List(); - data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log() { - var data = new List(); - data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log10() { - var data = new List(); - data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Pow() { - var data = new List(); - data.Add(select.Where(a => Math.Pow(2, a.Clicks % 5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sqrt() { - var data = new List(); - data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Cos() { - var data = new List(); - data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sin() { - var data = new List(); - data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Tan() { - var data = new List(); - data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Acos() { - var data = new List(); - //data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Asin() { - var data = new List(); - //data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan() { - var data = new List(); - data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan2() { - var data = new List(); - //data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Truncate() { - var data = new List(); - data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); - } - } + [Fact] + public void PI() + { + var data = new List(); + data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); + } + [Fact] + public void Abs() + { + var data = new List(); + data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Sign() + { + var data = new List(); + data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Floor() + { + var data = new List(); + data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); + } + [Fact] + public void Ceiling() + { + var data = new List(); + data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Round() + { + var data = new List(); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); + } + [Fact] + public void Exp() + { + var data = new List(); + data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log() + { + var data = new List(); + data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log10() + { + var data = new List(); + data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Pow() + { + var data = new List(); + data.Add(select.Where(a => Math.Pow(2, a.Clicks % 5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sqrt() + { + var data = new List(); + data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Cos() + { + var data = new List(); + data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sin() + { + var data = new List(); + data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Tan() + { + var data = new List(); + data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Acos() + { + var data = new List(); + //data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Asin() + { + var data = new List(); + //data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan() + { + var data = new List(); + data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan2() + { + var data = new List(); + //data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Truncate() + { + var data = new List(); + data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/OtherTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/OtherTest.cs index 60af2b04..512c1441 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/OtherTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/OtherTest.cs @@ -4,110 +4,116 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.OracleExpression { - public class OtherTest { +namespace FreeSql.Tests.OracleExpression +{ + public class OtherTest + { - ISelect select => g.oracle.Select(); + ISelect select => g.oracle.Select(); - public OtherTest() { - } + public OtherTest() + { + } - [Fact] - public void Boolean() { - var t1 = select.Where(a => a.Bool == true).ToList(); - var t2 = select.Where(a => a.Bool != true).ToList(); - var t3 = select.Where(a => a.Bool == false).ToList(); - var t4 = select.Where(a => !a.Bool).ToList(); - var t5 = select.Where(a => a.Bool).ToList(); + [Fact] + public void Boolean() + { + var t1 = select.Where(a => a.Bool == true).ToList(); + var t2 = select.Where(a => a.Bool != true).ToList(); + var t3 = select.Where(a => a.Bool == false).ToList(); + var t4 = select.Where(a => !a.Bool).ToList(); + var t5 = select.Where(a => a.Bool).ToList(); - var t11 = select.Where(a => a.BoolNullable == true).ToList(); - var t22 = select.Where(a => a.BoolNullable != true).ToList(); - var t33 = select.Where(a => a.BoolNullable == false).ToList(); - var t44 = select.Where(a => !a.BoolNullable.Value).ToList(); - var t55 = select.Where(a => a.BoolNullable.Value).ToList(); - } + var t11 = select.Where(a => a.BoolNullable == true).ToList(); + var t22 = select.Where(a => a.BoolNullable != true).ToList(); + var t33 = select.Where(a => a.BoolNullable == false).ToList(); + var t44 = select.Where(a => !a.BoolNullable.Value).ToList(); + var t55 = select.Where(a => a.BoolNullable.Value).ToList(); + } - [Fact] - public void Array() { - IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); - var testlinq = select.Where(a => testlinqlist.Contains(a.Int)).ToList(); + [Fact] + public void Array() + { + IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); + var testlinq = select.Where(a => testlinqlist.Contains(a.Int)).ToList(); - //in not in - var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.Int)).ToList(); - //var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.Int) == false).ToList(); - var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.Int)).ToList(); + //in not in + var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.Int)).ToList(); + //var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.Int) == false).ToList(); + var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.Int)).ToList(); - var inarray = new[] { 1, 2, 3 }; - var sql1111 = select.Where(a => inarray.Contains(a.Int)).ToList(); - //var sql1122 = select.Where(a => inarray.Contains(a.Int) == false).ToList(); - var sql1133 = select.Where(a => !inarray.Contains(a.Int)).ToList(); + var inarray = new[] { 1, 2, 3 }; + var sql1111 = select.Where(a => inarray.Contains(a.Int)).ToList(); + //var sql1122 = select.Where(a => inarray.Contains(a.Int) == false).ToList(); + var sql1133 = select.Where(a => !inarray.Contains(a.Int)).ToList(); - //in not in - var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.Int)).ToList(); - //var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.Int) == false).ToList(); - var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.Int)).ToList(); + //in not in + var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.Int)).ToList(); + //var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.Int) == false).ToList(); + var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.Int)).ToList(); - var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.Int)).ToList(); - //var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.Int) == false).ToList(); - var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.Int)).ToList(); + var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.Int)).ToList(); + //var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.Int) == false).ToList(); + var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.Int)).ToList(); - var inarray2 = new List() { 1, 2, 3 }; - var sql111111 = select.Where(a => inarray.Contains(a.Int)).ToList(); - //var sql112222 = select.Where(a => inarray.Contains(a.Int) == false).ToList(); - var sql113333 = select.Where(a => !inarray.Contains(a.Int)).ToList(); - } + var inarray2 = new List() { 1, 2, 3 }; + var sql111111 = select.Where(a => inarray.Contains(a.Int)).ToList(); + //var sql112222 = select.Where(a => inarray.Contains(a.Int) == false).ToList(); + var sql113333 = select.Where(a => !inarray.Contains(a.Int)).ToList(); + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - public string id2 { get; set; } = "id2=10"; + public string id2 { get; set; } = "id2=10"; - public bool Bool { get; set; } - public sbyte SByte { get; set; } - public short Short { get; set; } - public int Int { get; set; } - public long Long { get; set; } - public byte Byte { get; set; } - public ushort UShort { get; set; } - public uint UInt { get; set; } - public ulong ULong { get; set; } - public double Double { get; set; } - public float Float { get; set; } - public decimal Decimal { get; set; } - public TimeSpan TimeSpan { get; set; } - public DateTime DateTime { get; set; } - public DateTime DateTimeOffSet { get; set; } - public byte[] Bytes { get; set; } - public string String { get; set; } - public Guid Guid { get; set; } + public bool Bool { get; set; } + public sbyte SByte { get; set; } + public short Short { get; set; } + public int Int { get; set; } + public long Long { get; set; } + public byte Byte { get; set; } + public ushort UShort { get; set; } + public uint UInt { get; set; } + public ulong ULong { get; set; } + public double Double { get; set; } + public float Float { get; set; } + public decimal Decimal { get; set; } + public TimeSpan TimeSpan { get; set; } + public DateTime DateTime { get; set; } + public DateTime DateTimeOffSet { get; set; } + public byte[] Bytes { get; set; } + public string String { get; set; } + public Guid Guid { get; set; } - public bool? BoolNullable { get; set; } - public sbyte? SByteNullable { get; set; } - public short? ShortNullable { get; set; } - public int? IntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? ByteNullable { get; set; } - public ushort? UShortNullable { get; set; } - public uint? UIntNullable { get; set; } - public ulong? ULongNullable { get; set; } - public double? DoubleNullable { get; set; } - public float? FloatNullable { get; set; } - public decimal? DecimalNullable { get; set; } - public TimeSpan? TimeSpanNullable { get; set; } - public DateTime? DateTimeNullable { get; set; } - public DateTime? DateTimeOffSetNullable { get; set; } - public Guid? GuidNullable { get; set; } + public bool? BoolNullable { get; set; } + public sbyte? SByteNullable { get; set; } + public short? ShortNullable { get; set; } + public int? IntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? ByteNullable { get; set; } + public ushort? UShortNullable { get; set; } + public uint? UIntNullable { get; set; } + public ulong? ULongNullable { get; set; } + public double? DoubleNullable { get; set; } + public float? FloatNullable { get; set; } + public decimal? DecimalNullable { get; set; } + public TimeSpan? TimeSpanNullable { get; set; } + public DateTime? DateTimeNullable { get; set; } + public DateTime? DateTimeOffSetNullable { get; set; } + public Guid? GuidNullable { get; set; } - public TableAllTypeEnumType1 Enum1 { get; set; } - public TableAllTypeEnumType1? Enum1Nullable { get; set; } - public TableAllTypeEnumType2 Enum2 { get; set; } - public TableAllTypeEnumType2? Enum2Nullable { get; set; } - } + public TableAllTypeEnumType1 Enum1 { get; set; } + public TableAllTypeEnumType1? Enum1Nullable { get; set; } + public TableAllTypeEnumType2 Enum2 { get; set; } + public TableAllTypeEnumType2? Enum2Nullable { get; set; } + } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/StringTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/StringTest.cs index 0fb3456c..7d2017d1 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/StringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/StringTest.cs @@ -4,692 +4,716 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.OracleExpression { - public class StringTest { - - ISelect select => g.oracle.Select(); - - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - class TestEqualsGuid { - public Guid id { get; set; } - } - - [Fact] - public void Equals__() { - var list = new List(); - list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); - list.Add(g.oracle.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); - } - - - [Fact] - public void Empty() { - var data = new List(); - data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ifnull(a.`Title`, '') = '') - } - - [Fact] - public void StartsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) - list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) - } - [Fact] - public void EndsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) - } - [Fact] - public void Contains() { - var list = new List(); - list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) - } - [Fact] - public void ToLower() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void ToUpper() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void Substring() { - var data = new List(); - data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) - } - [Fact] - public void Length() { - var data = new List(); - data.Add(select.Where(a => a.Title.Length == 0).ToList()); - data.Add(select.Where(a => a.Title.Length == 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); - data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) - } - [Fact] - public void IndexOf() { - var data = new List(); - data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) - } - [Fact] - public void PadLeft() { - var data = new List(); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void PadRight() { - var data = new List(); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void Trim() { - var data = new List(); - data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void TrimStart() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) - } - [Fact] - public void TrimEnd() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void Replace() { - var data = new List(); - data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) - } - - [Fact] - public void string_IsNullOrEmpty() { - var data = new List(); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); - //data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); - data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); - } - } +namespace FreeSql.Tests.OracleExpression +{ + public class StringTest + { + + ISelect select => g.oracle.Select(); + + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + class TestEqualsGuid + { + public Guid id { get; set; } + } + + [Fact] + public void Equals__() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); + list.Add(g.oracle.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); + } + + + [Fact] + public void Empty() + { + var data = new List(); + data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ifnull(a.`Title`, '') = '') + } + + [Fact] + public void StartsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) + list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) + } + [Fact] + public void EndsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) + } + [Fact] + public void Contains() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) + } + [Fact] + public void ToLower() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void ToUpper() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void Substring() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) + } + [Fact] + public void Length() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Length == 0).ToList()); + data.Add(select.Where(a => a.Title.Length == 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); + data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) + } + [Fact] + public void IndexOf() + { + var data = new List(); + data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) + } + [Fact] + public void PadLeft() + { + var data = new List(); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void PadRight() + { + var data = new List(); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void Trim() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void TrimStart() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) + } + [Fact] + public void TrimEnd() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void Replace() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) + } + + [Fact] + public void string_IsNullOrEmpty() + { + var data = new List(); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); + //data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); + data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/TimeSpanTest.cs b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/TimeSpanTest.cs index 00e5491e..b1745d13 100644 --- a/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/TimeSpanTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Oracle/OracleExpression/TimeSpanTest.cs @@ -4,257 +4,290 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.OracleExpression { - public class TimeSpanTest { +namespace FreeSql.Tests.OracleExpression +{ + public class TimeSpanTest + { - ISelect select => g.oracle.Select(); + ISelect select => g.oracle.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } - [Fact] - public void Zero() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) - } - [Fact] - public void Days() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) - } - [Fact] - public void Hours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) - } - [Fact] - public void Milliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) - } - [Fact] - public void Minutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) - } - [Fact] - public void Seconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) - } - [Fact] - public void TotalDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) - } - [Fact] - public void TotalHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) - } - [Fact] - public void TotalMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) - } - [Fact] - public void TotalMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) - } - [Fact] - public void TotalSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') - } + public List Types { get; set; } + } + [Fact] + public void Zero() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) + } + [Fact] + public void Days() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) + } + [Fact] + public void Hours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) + } + [Fact] + public void Milliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) + } + [Fact] + public void Minutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) + } + [Fact] + public void Seconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) + } + [Fact] + public void TotalDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) + } + [Fact] + public void TotalHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) + } + [Fact] + public void TotalMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) + } + [Fact] + public void TotalMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) + } + [Fact] + public void TotalSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') + } - [Fact] - public void TimeSpan_Compare() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void TimeSpan_Equals() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromDays() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromHours() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) - } - [Fact] - public void TimeSpan_FromMilliseconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) - } - [Fact] - public void TimeSpan_FromMinutes() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) - } - [Fact] - public void TimeSpan_FromSeconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) - } - [Fact] - public void TimeSpan_FromTicks() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) - } - [Fact] - public void TimeSpan_Parse() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) - } - } + [Fact] + public void TimeSpan_Compare() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void TimeSpan_Equals() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromDays() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromHours() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) + } + [Fact] + public void TimeSpan_FromMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) + } + [Fact] + public void TimeSpan_FromMinutes() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) + } + [Fact] + public void TimeSpan_FromSeconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) + } + [Fact] + public void TimeSpan_FromTicks() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) + } + [Fact] + public void TimeSpan_Parse() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLDeleteTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLDeleteTest.cs index aad0a58b..360024bc 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLDeleteTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLDeleteTest.cs @@ -4,85 +4,94 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQL { - public class PostgreSQLDeleteTest { +namespace FreeSql.Tests.PostgreSQL +{ + public class PostgreSQLDeleteTest + { - IDelete delete => g.pgsql.Delete(); + IDelete delete => g.pgsql.Delete(); - [Table(Name = "tb_topic_del")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } + [Table(Name = "tb_topic_del")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void Dywhere() { - Assert.Null(g.pgsql.Delete().ToSql()); - var sql = g.pgsql.Delete(new[] { 1, 2 }).ToSql(); - Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1 OR \"id\" = 2)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(g.pgsql.Delete().ToSql()); + var sql = g.pgsql.Delete(new[] { 1, 2 }).ToSql(); + Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1 OR \"id\" = 2)", sql); - sql = g.pgsql.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); - Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1)", sql); + sql = g.pgsql.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); + Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1)", sql); - sql = g.pgsql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); - Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1 OR \"id\" = 2)", sql); + sql = g.pgsql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); + Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1 OR \"id\" = 2)", sql); - sql = g.pgsql.Delete(new { id = 1 }).ToSql(); - Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1)", sql); - } + sql = g.pgsql.Delete(new { id = 1 }).ToSql(); + Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1)", sql); + } - [Fact] - public void Where() { - var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1)", sql); + [Fact] + public void Where() + { + var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1)", sql); - sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (id = @id)", sql); + sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (id = @id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = delete.Where(item).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = delete.Where(item).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = delete.Where(items).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + sql = delete.Where(items).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"tb_topic_del\" WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - var id = g.pgsql.Insert(new Topic { Title = "xxxx" }).ExecuteIdentity(); - Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); - } - [Fact] - public void ExecuteDeleted() { + var id = g.pgsql.Insert(new Topic { Title = "xxxx" }).ExecuteIdentity(); + Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); + } + [Fact] + public void ExecuteDeleted() + { - delete.Where(a => a.Id > 0).ExecuteDeleted(); - } + delete.Where(a => a.Id > 0).ExecuteDeleted(); + } - [Fact] - public void AsTable() { - Assert.Null(g.pgsql.Delete().ToSql()); - var sql = g.pgsql.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"id\" = 1 OR \"id\" = 2)", sql); + [Fact] + public void AsTable() + { + Assert.Null(g.pgsql.Delete().ToSql()); + var sql = g.pgsql.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"id\" = 1 OR \"id\" = 2)", sql); - sql = g.pgsql.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"id\" = 1)", sql); + sql = g.pgsql.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"id\" = 1)", sql); - sql = g.pgsql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"id\" = 1 OR \"id\" = 2)", sql); + sql = g.pgsql.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"id\" = 1 OR \"id\" = 2)", sql); - sql = g.pgsql.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"id\" = 1)", sql); - } - } + sql = g.pgsql.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"id\" = 1)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLInsertTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLInsertTest.cs index b9de2ad9..877650ac 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLInsertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLInsertTest.cs @@ -4,112 +4,122 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQL { - public class PostgreSQLInsertTest { +namespace FreeSql.Tests.PostgreSQL +{ + public class PostgreSQLInsertTest + { - IInsert insert => g.pgsql.Insert(); + IInsert insert => g.pgsql.Insert(); - [Table(Name = "tb_topic_insert")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - - [Fact] - public void AppendData() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + [Table(Name = "tb_topic_insert")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - var sql = insert.AppendData(items.First()).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\", \"createtime\") VALUES(@clicks_0, @title_0, @createtime_0)", sql); + [Fact] + public void AppendData() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\", \"createtime\") VALUES(@clicks_0, @title_0, @createtime_0), (@clicks_1, @title_1, @createtime_1), (@clicks_2, @title_2, @createtime_2), (@clicks_3, @title_3, @createtime_3), (@clicks_4, @title_4, @createtime_4), (@clicks_5, @title_5, @createtime_5), (@clicks_6, @title_6, @createtime_6), (@clicks_7, @title_7, @createtime_7), (@clicks_8, @title_8, @createtime_8), (@clicks_9, @title_9, @createtime_9)", sql); + var sql = insert.AppendData(items.First()).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\", \"createtime\") VALUES(@clicks_0, @title_0, @createtime_0)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"title\") VALUES(@title_0), (@title_1), (@title_2), (@title_3), (@title_4), (@title_5), (@title_6), (@title_7), (@title_8), (@title_9)", sql); + sql = insert.AppendData(items).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\", \"createtime\") VALUES(@clicks_0, @title_0, @createtime_0), (@clicks_1, @title_1, @createtime_1), (@clicks_2, @title_2, @createtime_2), (@clicks_3, @title_3, @createtime_3), (@clicks_4, @title_4, @createtime_4), (@clicks_5, @title_5, @createtime_5), (@clicks_6, @title_6, @createtime_6), (@clicks_7, @title_7, @createtime_7), (@clicks_8, @title_8, @createtime_8), (@clicks_9, @title_9, @createtime_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); - } + sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"title\") VALUES(@title_0), (@title_1), (@title_2), (@title_3), (@title_4), (@title_5), (@title_6), (@title_7), (@title_8), (@title_9)", sql); - [Fact] - public void InsertColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); + } - var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"title\") VALUES(@title_0), (@title_1), (@title_2), (@title_3), (@title_4), (@title_5), (@title_6), (@title_7), (@title_8), (@title_9)", sql); + [Fact] + public void InsertColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).InsertColumns(a =>new { a.Title, a.Clicks }).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); - } - [Fact] - public void IgnoreColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"title\") VALUES(@title_0), (@title_1), (@title_2), (@title_3), (@title_4), (@title_5), (@title_6), (@title_7), (@title_8), (@title_9)", sql); - var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); + } + [Fact] + public void IgnoreColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\") VALUES(@clicks_0), (@clicks_1), (@clicks_2), (@clicks_3), (@clicks_4), (@clicks_5), (@clicks_6), (@clicks_7), (@clicks_8), (@clicks_9)", sql); - } - [Fact] - public void ExecuteAffrows() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); - Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); - } - [Fact] - public void ExecuteIdentity() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"clicks\") VALUES(@clicks_0), (@clicks_1), (@clicks_2), (@clicks_3), (@clicks_4), (@clicks_5), (@clicks_6), (@clicks_7), (@clicks_8), (@clicks_9)", sql); + } + [Fact] + public void ExecuteAffrows() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); - } - [Fact] - public void ExecuteInserted() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); + } + [Fact] + public void ExecuteIdentity() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - insert.AppendData(items.First()).ExecuteInserted(); - } + Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); + } + [Fact] + public void ExecuteInserted() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - [Fact] - public void AsTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + insert.AppendData(items.First()).ExecuteInserted(); + } - var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\", \"createtime\") VALUES(@clicks_0, @title_0, @createtime_0)", sql); + [Fact] + public void AsTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\", \"createtime\") VALUES(@clicks_0, @title_0, @createtime_0), (@clicks_1, @title_1, @createtime_1), (@clicks_2, @title_2, @createtime_2), (@clicks_3, @title_3, @createtime_3), (@clicks_4, @title_4, @createtime_4), (@clicks_5, @title_5, @createtime_5), (@clicks_6, @title_6, @createtime_6), (@clicks_7, @title_7, @createtime_7), (@clicks_8, @title_8, @createtime_8), (@clicks_9, @title_9, @createtime_9)", sql); + var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\", \"createtime\") VALUES(@clicks_0, @title_0, @createtime_0)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"title\") VALUES(@title_0), (@title_1), (@title_2), (@title_3), (@title_4), (@title_5), (@title_6), (@title_7), (@title_8), (@title_9)", sql); + sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\", \"createtime\") VALUES(@clicks_0, @title_0, @createtime_0), (@clicks_1, @title_1, @createtime_1), (@clicks_2, @title_2, @createtime_2), (@clicks_3, @title_3, @createtime_3), (@clicks_4, @title_4, @createtime_4), (@clicks_5, @title_5, @createtime_5), (@clicks_6, @title_6, @createtime_6), (@clicks_7, @title_7, @createtime_7), (@clicks_8, @title_8, @createtime_8), (@clicks_9, @title_9, @createtime_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"title\") VALUES(@title_0), (@title_1), (@title_2), (@title_3), (@title_4), (@title_5), (@title_6), (@title_7), (@title_8), (@title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"title\") VALUES(@title_0), (@title_1), (@title_2), (@title_3), (@title_4), (@title_5), (@title_6), (@title_7), (@title_8), (@title_9)", sql); + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"title\") VALUES(@title_0), (@title_1), (@title_2), (@title_3), (@title_4), (@title_5), (@title_6), (@title_7), (@title_8), (@title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\") VALUES(@clicks_0), (@clicks_1), (@clicks_2), (@clicks_3), (@clicks_4), (@clicks_5), (@clicks_6), (@clicks_7), (@clicks_8), (@clicks_9)", sql); - } - } + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\", \"title\") VALUES(@clicks_0, @title_0), (@clicks_1, @title_1), (@clicks_2, @title_2), (@clicks_3, @title_3), (@clicks_4, @title_4), (@clicks_5, @title_5), (@clicks_6, @title_6), (@clicks_7, @title_7), (@clicks_8, @title_8), (@clicks_9, @title_9)", sql); + + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"clicks\") VALUES(@clicks_0), (@clicks_1), (@clicks_2), (@clicks_3), (@clicks_4), (@clicks_5), (@clicks_6), (@clicks_7), (@clicks_8), (@clicks_9)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLSelectTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLSelectTest.cs index b4ac0f9f..a6bc17c1 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLSelectTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLSelectTest.cs @@ -4,1179 +4,1256 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQL { - public class PostgreSQLSelectTest { - - ISelect select => g.pgsql.Select(); - - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - public partial class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } - - public virtual ICollection Tags { get; set; } - } - public partial class Song_tag { - public int Song_id { get; set; } - public virtual Song Song { get; set; } - - public int Tag_id { get; set; } - public virtual Tag Tag { get; set; } - } - public partial class Tag { - [Column(IsIdentity = true)] - public int Id { get; set; } - public int? Parent_id { get; set; } - public virtual Tag Parent { get; set; } - - public decimal? Ddd { get; set; } - public string Name { get; set; } - - public virtual ICollection Songs { get; set; } - public virtual ICollection Tags { get; set; } - } - - [Fact] - public void AsSelect() { - //OneToOne、ManyToOne - var t0 = g.pgsql.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 - //FROM `Tag` a - //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` - //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` - //WHERE (a__Parent__Parent.`Name` = '粤语') - - //OneToMany - var t1 = g.pgsql.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` - //FROM `Tag` a - //WHERE (exists(SELECT 1 - // FROM `Tag` t - // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` - // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) - // limit 0,1)) - - //ManyToMany - var t2 = g.pgsql.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); - //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` - //FROM `Song` a - //WHERE(exists(SELECT 1 - // FROM `Song_tag` Mt_Ms - // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 - // FROM `Tag` t - // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) - // limit 0, 1)) - // limit 0, 1)) - } - - [Fact] - public void Lazy() { - var tags = g.pgsql.Select().Where(a => a.Parent.Name == "xxx") - .LeftJoin(a => a.Parent_id == a.Parent.Id) - .ToSql(); - - var songs = g.pgsql.Select().Limit(10).ToList(); - } - - [Fact] - public void ToDataTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - - Assert.Single(g.pgsql.Insert().AppendData(items.First()).ExecuteInserted()); - Assert.Equal(10, g.pgsql.Insert().AppendData(items).ExecuteInserted().Count); - - //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - //Assert.Equal(9989, g.pgsql.Insert(items).ExecuteAffrows()); - - var dt1 = select.Limit(10).ToDataTable(); - var dt2 = select.Limit(10).ToDataTable("id, 222"); - var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); - } - class TestDto { - public int id { get; set; } - public string name { get; set; } //这是join表的属性 - public int ParentId { get; set; } //这是join表的属性 - } - [Fact] - public void ToList() { - - var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto2 = select.Limit(10).ToList(a => new TestDto()); - var testDto3 = select.Limit(10).ToList(a => new TestDto { }); - var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); - - var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); - var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); - var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); - - - var t1 = g.pgsql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); - var t2 = g.pgsql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); - - - var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToSql(); - var sql2 = select.LeftJoin((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToSql(); - var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToSql(); - - //g.pgsql.Select().Join((a, b, c) => new Model.JoinResult3( - // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, - // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") - //); - - //var sql4 = select.From((a, b, c) => new SelectFrom() - // .InnerJoin(a.TypeGuid == b.Guid) - // .LeftJoin(c.Id == b.ParentId) - // .Where(b.Name == "xxx")) - //.Where(a => a.Id == 1).ToSql(); - - var sql4 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => c.Id == b.ParentId) - .Where(a => b.Name == "xxx")).ToSql(); - //.Where(a => a.Id == 1).ToSql(); - - - var list111 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => c.Id == b.ParentId) - .Where(a => b.Name != "xxx")); - var list111sql = list111.ToSql(); - var list111data = list111.ToList((a, b, c) => new { - a.Id, - title_substring = a.Title.Substring(0, 1), - a.Type, - ccc = new { a.Id, a.Title }, - tp = a.Type, - tp2 = new { - a.Id, - tp2 = a.Type.Name - }, - tp3 = new { - a.Id, - tp33 = new { - a.Id - } - } - }); - - var ttt122 = g.pgsql.Select().Where(a => a.Id > 0).ToSql(); - var sql5 = g.pgsql.Select().From((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToSql(); - var t11112 = g.pgsql.Select().ToList(a => new { - a.Id, - a.Title, - a.Type, - ccc = new { a.Id, a.Title }, - tp = a.Type, - tp2 = new { - a.Id, - tp2 = a.Type.Name - }, - tp3 = new { - a.Id, - tp33 = new { - a.Id - } - } - - }); - - var t100 = g.pgsql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - var t101 = g.pgsql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - - - var t1111 = g.pgsql.Select().ToList(a => new { a.Id, a.Title, a.Type }); - - var t2222 = g.pgsql.Select().ToList(a => new { a.Id, a.Title, a.Type.Name }); - - g.pgsql.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); - var testGuidId5 = g.pgsql.Select().ToList(); - var testGuidId6 = g.pgsql.Select().ToList(a => a.id); - - var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); - var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); - } - class TestGuidIdToList { - public Guid id { get; set; } - public string title { get; set; } = Guid.NewGuid().ToString(); - } - [Fact] - public void ToOne() { - var testnotfind = select.Where("1=2").First(a => a.CreateTime); - Assert.Equal(default(DateTime), testnotfind); - } - [Fact] - public void ToSql() { - } - [Fact] - public void Any() { - var count = select.Where(a => 1 == 1).Count(); - Assert.False(select.Where(a => 1 == 2).Any()); - Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); - - var sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && - select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - //.Offset(a.Id) - .Any() - ).Any(c => c.Id == a.Id + 10) - ); - var sql2222Tolist = sql2222.ToList(); - - var collectionSelect = select.Where(a => - a.Type.Guid == a.TypeGuid && - a.Type.Parent.Id == a.Type.ParentId && - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) - ); - collectionSelect.ToList(); - } - [Fact] - public void Count() { - var count = select.Where(a => 1 == 1).Count(); - select.Where(a => 1 == 1).Count(out var count2); - Assert.Equal(count, count2); - Assert.Equal(0, select.Where(a => 1 == 2).Count()); - } - [Fact] - public void Master() { - Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); - } - - [Fact] - public void From() { - - var query2 = select.From((s, b) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - ); - var sql2 = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\"", sql2); - query2.ToList(); - - var query3 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id) - ); - var sql3 = query3.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\" LEFT JOIN \"testtypeparentinfo\" c ON b.\"parentid\" = c.\"id\"", sql3); - query3.ToList(); - } - [Fact] - public void LeftJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); - query.ToList(); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\"", sql); - query.ToList(); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfo\" c ON c.\"id\" = a__Type.\"parentid\"", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\" LEFT JOIN \"testtypeparentinfo\" c ON b.\"parentid\" = c.\"id\"", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.LeftJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\""); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.LeftJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", sql); - query.ToList(); - } - [Fact] - public void InnerJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); - query.ToList(); - - //������� - query = select - .InnerJoin(a => a.Type.Guid == a.TypeGuid) - .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" INNER JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\"", sql); - query.ToList(); - - query = select - .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .InnerJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" INNER JOIN \"testtypeparentinfo\" c ON c.\"id\" = a__Type.\"parentid\"", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .InnerJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\" INNER JOIN \"testtypeparentinfo\" c ON b.\"parentid\" = c.\"id\"", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.InnerJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\""); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.InnerJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", sql); - query.ToList(); - - } - [Fact] - public void RightJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); - query.ToList(); - - //������� - query = select - .RightJoin(a => a.Type.Guid == a.TypeGuid) - .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" RIGHT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\"", sql); - query.ToList(); - - query = select - .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .RightJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" RIGHT JOIN \"testtypeparentinfo\" c ON c.\"id\" = a__Type.\"parentid\"", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .RightJoin(a => a.TypeGuid == b.Guid) - .RightJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\" RIGHT JOIN \"testtypeparentinfo\" c ON b.\"parentid\" = c.\"id\"", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.RightJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\""); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"", sql); - query.ToList(); - - query = select.RightJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", sql); - query.ToList(); - - } - [Fact] - public void Where() { - var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); - var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); - var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); - - var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.Where(a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"id\" = 10)", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE ((a.\"id\" = 10 AND a.\"id\" > 10 OR a.\"clicks\" > 100))", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"id\" = 10) AND (a.\"clicks\" > 100)", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" WHERE (a__Type.\"name\" = 'typeTitle')", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" WHERE (a__Type.\"name\" = 'typeTitle' AND a__Type.\"guid\" = a.\"typeguid\")", sql); - query.ToList(); - - query = select.Where(a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"name\" = 'tparent')", sql); - query.ToList(); - - //���û�е������ԣ��򵥶������ - query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b WHERE (b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'typeTitle')", sql); - query.ToList(); - - query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b WHERE (b.\"name\" = 'typeTitle' AND b.\"guid\" = a.\"typeguid\")", sql); - query.ToList(); - - query = select.Where((a, b, c) => c.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeparentinfo\" c WHERE (c.\"name\" = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .Where(a => a.Id == 10 && c.Name == "xxx") - .Where(a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b, \"testtypeparentinfo\" c WHERE (a.\"id\" = 10 AND c.\"name\" = 'xxx') AND (b.\"parentid\" = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.Where("a.\"clicks\" > 100 and a.\"id\" = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"clicks\" > 100 and a.\"id\" = @id)", sql); - query.ToList(); - } - [Fact] - public void WhereIf() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.WhereIf(true, a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"id\" = 10)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE ((a.\"id\" = 10 AND a.\"id\" > 10 OR a.\"clicks\" > 100))", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"id\" = 10) AND (a.\"clicks\" > 100)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" WHERE (a__Type.\"name\" = 'typeTitle')", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" WHERE (a__Type.\"name\" = 'typeTitle' AND a__Type.\"guid\" = a.\"typeguid\")", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"name\" = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(true, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b, \"testtypeparentinfo\" c WHERE (a.\"id\" = 10 AND c.\"name\" = 'xxx') AND (b.\"parentid\" = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(true, "a.\"clicks\" > 100 and a.\"id\" = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"clicks\" > 100 and a.\"id\" = @id)", sql); - query.ToList(); - - // ==========================================WhereIf(false) - - //����е�������a.Type��a.Type.Parent ���ǵ������� - query = select.WhereIf(false, a => a.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - query2 = select.From((s, b, c) => s - .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(false, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b, \"testtypeparentinfo\" c", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(false, "a.\"clicks\" > 100 and a.\"id\" = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); - query.ToList(); - } - [Fact] - public void WhereExists() { - var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); - - sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - - //.Offset(a.Id) - - .Any() - ).Any() - ).ToList(); - } - [Fact] - public void GroupBy() { - var groupby = select.From((s, b, c) => s - .Where(a => a.Id == 1) - ) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()) - .Offset(10) - .Limit(2) - .ToList(a => new { - a.Key.tt2, - cou1 = a.Count(), - arg1 = a.Avg(a.Key.mod4), - ccc2 = a.Key.tt2 ?? "now()", - //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") - ccc3 = a.Max(a.Value.Item3.Id) - }); - - var testpid1 = g.pgsql.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); - g.pgsql.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); - - var aggsql1 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist1 = select - .GroupBy(a => a.Title) - .ToList(b => new { - b.Key, - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToSql(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToList(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql3 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid), - sum3 = b.Sum(b.Value.Type.Parent.Id) - }); - } - [Fact] - public void ToAggregate() { - var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); - } - [Fact] - public void OrderBy() { - var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); - } - [Fact] - public void Skip_Offset() { - var sql = select.Offset(10).Limit(10).ToList(); - } - [Fact] - public void Take_Limit() { - var sql = select.Limit(10).ToList(); - } - [Fact] - public void Page() { - var sql1 = select.Page(1, 10).ToList(); - var sql2 = select.Page(2, 10).ToList(); - var sql3 = select.Page(3, 10).ToList(); - - var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); - var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); - var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); - } - [Fact] - public void Distinct() { - var t1 = select.Distinct().ToList(a => a.Title); - var t2 = select.Distinct().Limit(10).ToList(a => a.Title); - } - - [Fact] - public void Sum() { - } - [Fact] - public void Min() { - } - [Fact] - public void Max() { - } - [Fact] - public void Avg() { - } - [Fact] - public void As() { - } - - [Fact] - public void AsTable() { - - var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); - - Func tableRule = (type, oldname) => { - if (type == typeof(Topic)) return oldname + "AsTable1"; - else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; - return oldname + "AsTable"; - }; - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\"", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx'", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfoAsTable\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" b ON b.\"guid\" = a.\"typeguid\"", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" b ON b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'xxx'", sql); - - query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfoAsTable\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfoAsTable\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\"", sql); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfoAsTable\" c ON c.\"id\" = a__Type.\"parentid\"", sql); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" b ON a.\"typeguid\" = b.\"guid\" LEFT JOIN \"testtypeparentinfoAsTable\" c ON b.\"parentid\" = c.\"id\"", sql); - - //������϶����㲻�� - query = select.LeftJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"", sql); - - query = select.LeftJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", new { bname = "xxx" }).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", sql); - } - - public class TestInclude_OneToManyModel1 { - [Column(IsIdentity = true)] - public int id { get; set; } - public virtual TestInclude_OneToManyModel2 model2 { get; set; } - - public string m1name { get; set; } - } - public class TestInclude_OneToManyModel2 { - [Column(IsPrimary = true)] - public int model2id { get; set; } - public virtual TestInclude_OneToManyModel1 model1 { get; set; } - - public string m2setting { get; set; } - - public List childs { get; set; } - } - public class TestInclude_OneToManyModel3 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model2111Idaaa { get; set; } - public string title { get; set; } - - public List childs2 { get; set; } - } - public class TestInclude_OneToManyModel4 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model3333Id333 { get; set; } - public string title444 { get; set; } - } - - [Fact] - public void Include_OneToMany() { - var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; - model1.id = (int)g.pgsql.Insert(model1).ExecuteIdentity(); - var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; - g.pgsql.Insert(model2).ExecuteAffrows(); - - var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; - model3_1.id = (int)g.pgsql.Insert(model3_1).ExecuteIdentity(); - var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; - model3_2.id = (int)g.pgsql.Insert(model3_2).ExecuteIdentity(); - var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; - model3_3.id = (int)g.pgsql.Insert(model3_2).ExecuteIdentity(); - - var model4s = new[] { - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } - }; - Assert.Equal(5, g.pgsql.Insert(model4s).ExecuteAffrows()); - - var t0 = g.pgsql.Select() - .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t1 = g.pgsql.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t2 = g.pgsql.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - - var t00 = g.pgsql.Select() - .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t11 = g.pgsql.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t22 = g.pgsql.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - } - - public class TestInclude_OneToManyModel11 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2id { get; set; } - public string m3setting { get; set; } - public TestInclude_OneToManyModel22 model2 { get; set; } - public string m1name { get; set; } - } - - public class TestInclude_OneToManyModel22 { - [Column(IsIdentity = true)] - public int id { get; set; } - public string m2setting { get; set; } - public List childs { get; set; } - } - public class TestInclude_OneToManyModel33 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2Id { get; set; } - public string title { get; set; } - public string setting { get; set; } - } - [Fact] - public void Include_OneToMany2() { - string setting = "x"; - var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; - model2.id = (int)g.pgsql.Insert(model2).ExecuteIdentity(); - - var model3s = new[] - { - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} - }; - Assert.Equal(3, g.pgsql.Insert(model3s).ExecuteAffrows()); - - var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; - model1.id = (int)g.pgsql.Insert(model1).ExecuteIdentity(); - - var t1 = g.pgsql.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - - var t11 = g.pgsql.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - } - - [Fact] - public void Include_OneToChilds() { - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_中国" - }; - tag1.Id = (int)g.pgsql.Insert(tag1).ExecuteIdentity(); - var tag1_1 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_北京" - }; - tag1_1.Id = (int)g.pgsql.Insert(tag1_1).ExecuteIdentity(); - var tag1_2 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_上海" - }; - tag1_2.Id = (int)g.pgsql.Insert(tag1_2).ExecuteIdentity(); - - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_美国" - }; - tag2.Id = (int)g.pgsql.Insert(tag2).ExecuteIdentity(); - var tag2_1 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_纽约" - }; - tag2_1.Id = (int)g.pgsql.Insert(tag2_1).ExecuteIdentity(); - var tag2_2 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_华盛顿" - }; - tag2_2.Id = (int)g.pgsql.Insert(tag2_2).ExecuteIdentity(); - - var tags0 = g.pgsql.Select() - .Include(a => a.Parent) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags1 = g.pgsql.Select() - .IncludeMany(a => a.Tags) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags2 = g.pgsql.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags3 = g.pgsql.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags11 = g.pgsql.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags22 = g.pgsql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags33 = g.pgsql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - } - - [Fact] - public void Include_ManyToMany() { - - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_01_中国" - }; - tag1.Id = (int)g.pgsql.Insert(tag1).ExecuteIdentity(); - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_02_美国" - }; - tag2.Id = (int)g.pgsql.Insert(tag2).ExecuteIdentity(); - var tag3 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_03_日本" - }; - tag3.Id = (int)g.pgsql.Insert(tag3).ExecuteIdentity(); - - var song1 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_01_我是中国人.mp3", - Url = "http://ww.baidu.com/" - }; - song1.Id = (int)g.pgsql.Insert(song1).ExecuteIdentity(); - var song2 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_02_爱你一万年.mp3", - Url = "http://ww.163.com/" - }; - song2.Id = (int)g.pgsql.Insert(song2).ExecuteIdentity(); - var song3 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_03_千年等一回.mp3", - Url = "http://ww.sina.com/" - }; - song3.Id = (int)g.pgsql.Insert(song3).ExecuteIdentity(); - - g.pgsql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.pgsql.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.pgsql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.pgsql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.pgsql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.pgsql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); - - var songs1 = g.pgsql.Select() - .IncludeMany(a => a.Tags) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs1.Count); - Assert.Equal(2, songs1[0].Tags.Count); - Assert.Equal(1, songs1[1].Tags.Count); - Assert.Equal(3, songs1[2].Tags.Count); - - var songs2 = g.pgsql.Select() - .IncludeMany(a => a.Tags, - then => then.IncludeMany(t => t.Songs)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs2.Count); - Assert.Equal(2, songs2[0].Tags.Count); - Assert.Equal(1, songs2[1].Tags.Count); - Assert.Equal(3, songs2[2].Tags.Count); - - var tags3 = g.pgsql.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - - - var songs11 = g.pgsql.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs11.Count); - Assert.Equal(1, songs11[0].Tags.Count); - Assert.Equal(1, songs11[1].Tags.Count); - Assert.Equal(1, songs11[2].Tags.Count); - - var songs22 = g.pgsql.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.IncludeMany(t => t.Songs.Take(1))) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs22.Count); - Assert.Equal(1, songs22[0].Tags.Count); - Assert.Equal(1, songs22[1].Tags.Count); - Assert.Equal(1, songs22[2].Tags.Count); - - var tags33 = g.pgsql.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs.Take(1)) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - } - } +namespace FreeSql.Tests.PostgreSQL +{ + public class PostgreSQLSelectTest + { + + ISelect select => g.pgsql.Select(); + + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + public partial class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } + + public virtual ICollection Tags { get; set; } + } + public partial class Song_tag + { + public int Song_id { get; set; } + public virtual Song Song { get; set; } + + public int Tag_id { get; set; } + public virtual Tag Tag { get; set; } + } + public partial class Tag + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public int? Parent_id { get; set; } + public virtual Tag Parent { get; set; } + + public decimal? Ddd { get; set; } + public string Name { get; set; } + + public virtual ICollection Songs { get; set; } + public virtual ICollection Tags { get; set; } + } + + [Fact] + public void AsSelect() + { + //OneToOne、ManyToOne + var t0 = g.pgsql.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 + //FROM `Tag` a + //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` + //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` + //WHERE (a__Parent__Parent.`Name` = '粤语') + + //OneToMany + var t1 = g.pgsql.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` + //FROM `Tag` a + //WHERE (exists(SELECT 1 + // FROM `Tag` t + // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` + // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) + // limit 0,1)) + + //ManyToMany + var t2 = g.pgsql.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); + //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` + //FROM `Song` a + //WHERE(exists(SELECT 1 + // FROM `Song_tag` Mt_Ms + // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 + // FROM `Tag` t + // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) + // limit 0, 1)) + // limit 0, 1)) + } + + [Fact] + public void Lazy() + { + var tags = g.pgsql.Select().Where(a => a.Parent.Name == "xxx") + .LeftJoin(a => a.Parent_id == a.Parent.Id) + .ToSql(); + + var songs = g.pgsql.Select().Limit(10).ToList(); + } + + [Fact] + public void ToDataTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + + Assert.Single(g.pgsql.Insert().AppendData(items.First()).ExecuteInserted()); + Assert.Equal(10, g.pgsql.Insert().AppendData(items).ExecuteInserted().Count); + + //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + //Assert.Equal(9989, g.pgsql.Insert(items).ExecuteAffrows()); + + var dt1 = select.Limit(10).ToDataTable(); + var dt2 = select.Limit(10).ToDataTable("id, 222"); + var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); + } + class TestDto + { + public int id { get; set; } + public string name { get; set; } //这是join表的属性 + public int ParentId { get; set; } //这是join表的属性 + } + [Fact] + public void ToList() + { + + var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto2 = select.Limit(10).ToList(a => new TestDto()); + var testDto3 = select.Limit(10).ToList(a => new TestDto { }); + var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); + + var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); + var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); + var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); + + + var t1 = g.pgsql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); + var t2 = g.pgsql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToSql(); + + + var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToSql(); + var sql2 = select.LeftJoin((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToSql(); + var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToSql(); + + //g.pgsql.Select().Join((a, b, c) => new Model.JoinResult3( + // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, + // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") + //); + + //var sql4 = select.From((a, b, c) => new SelectFrom() + // .InnerJoin(a.TypeGuid == b.Guid) + // .LeftJoin(c.Id == b.ParentId) + // .Where(b.Name == "xxx")) + //.Where(a => a.Id == 1).ToSql(); + + var sql4 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => c.Id == b.ParentId) + .Where(a => b.Name == "xxx")).ToSql(); + //.Where(a => a.Id == 1).ToSql(); + + + var list111 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => c.Id == b.ParentId) + .Where(a => b.Name != "xxx")); + var list111sql = list111.ToSql(); + var list111data = list111.ToList((a, b, c) => new + { + a.Id, + title_substring = a.Title.Substring(0, 1), + a.Type, + ccc = new { a.Id, a.Title }, + tp = a.Type, + tp2 = new + { + a.Id, + tp2 = a.Type.Name + }, + tp3 = new + { + a.Id, + tp33 = new + { + a.Id + } + } + }); + + var ttt122 = g.pgsql.Select().Where(a => a.Id > 0).ToSql(); + var sql5 = g.pgsql.Select().From((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToSql(); + var t11112 = g.pgsql.Select().ToList(a => new + { + a.Id, + a.Title, + a.Type, + ccc = new { a.Id, a.Title }, + tp = a.Type, + tp2 = new + { + a.Id, + tp2 = a.Type.Name + }, + tp3 = new + { + a.Id, + tp33 = new + { + a.Id + } + } + + }); + + var t100 = g.pgsql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + var t101 = g.pgsql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + + + var t1111 = g.pgsql.Select().ToList(a => new { a.Id, a.Title, a.Type }); + + var t2222 = g.pgsql.Select().ToList(a => new { a.Id, a.Title, a.Type.Name }); + + g.pgsql.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); + var testGuidId5 = g.pgsql.Select().ToList(); + var testGuidId6 = g.pgsql.Select().ToList(a => a.id); + + var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); + var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); + } + class TestGuidIdToList + { + public Guid id { get; set; } + public string title { get; set; } = Guid.NewGuid().ToString(); + } + [Fact] + public void ToOne() + { + var testnotfind = select.Where("1=2").First(a => a.CreateTime); + Assert.Equal(default(DateTime), testnotfind); + } + [Fact] + public void ToSql() + { + } + [Fact] + public void Any() + { + var count = select.Where(a => 1 == 1).Count(); + Assert.False(select.Where(a => 1 == 2).Any()); + Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); + + var sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && + select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + //.Offset(a.Id) + .Any() + ).Any(c => c.Id == a.Id + 10) + ); + var sql2222Tolist = sql2222.ToList(); + + var collectionSelect = select.Where(a => + a.Type.Guid == a.TypeGuid && + a.Type.Parent.Id == a.Type.ParentId && + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) + ); + collectionSelect.ToList(); + } + [Fact] + public void Count() + { + var count = select.Where(a => 1 == 1).Count(); + select.Where(a => 1 == 1).Count(out var count2); + Assert.Equal(count, count2); + Assert.Equal(0, select.Where(a => 1 == 2).Count()); + } + [Fact] + public void Master() + { + Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); + } + + [Fact] + public void From() + { + + var query2 = select.From((s, b) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + ); + var sql2 = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\"", sql2); + query2.ToList(); + + var query3 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id) + ); + var sql3 = query3.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\" LEFT JOIN \"testtypeparentinfo\" c ON b.\"parentid\" = c.\"id\"", sql3); + query3.ToList(); + } + [Fact] + public void LeftJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); + query.ToList(); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\"", sql); + query.ToList(); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfo\" c ON c.\"id\" = a__Type.\"parentid\"", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\" LEFT JOIN \"testtypeparentinfo\" c ON b.\"parentid\" = c.\"id\"", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.LeftJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\""); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.LeftJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", sql); + query.ToList(); + } + [Fact] + public void InnerJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); + query.ToList(); + + //������� + query = select + .InnerJoin(a => a.Type.Guid == a.TypeGuid) + .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" INNER JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\"", sql); + query.ToList(); + + query = select + .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .InnerJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" INNER JOIN \"testtypeparentinfo\" c ON c.\"id\" = a__Type.\"parentid\"", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .InnerJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\" INNER JOIN \"testtypeparentinfo\" c ON b.\"parentid\" = c.\"id\"", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.InnerJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\""); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.InnerJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a INNER JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", sql); + query.ToList(); + + } + [Fact] + public void RightJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b ON b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); + query.ToList(); + + //������� + query = select + .RightJoin(a => a.Type.Guid == a.TypeGuid) + .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" RIGHT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\"", sql); + query.ToList(); + + query = select + .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .RightJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" RIGHT JOIN \"testtypeparentinfo\" c ON c.\"id\" = a__Type.\"parentid\"", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .RightJoin(a => a.TypeGuid == b.Guid) + .RightJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b ON a.\"typeguid\" = b.\"guid\" RIGHT JOIN \"testtypeparentinfo\" c ON b.\"parentid\" = c.\"id\"", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.RightJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\""); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"", sql); + query.ToList(); + + query = select.RightJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a RIGHT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", sql); + query.ToList(); + + } + [Fact] + public void Where() + { + var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); + var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); + var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); + + var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.Where(a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"id\" = 10)", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE ((a.\"id\" = 10 AND a.\"id\" > 10 OR a.\"clicks\" > 100))", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"id\" = 10) AND (a.\"clicks\" > 100)", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" WHERE (a__Type.\"name\" = 'typeTitle')", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" WHERE (a__Type.\"name\" = 'typeTitle' AND a__Type.\"guid\" = a.\"typeguid\")", sql); + query.ToList(); + + query = select.Where(a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"name\" = 'tparent')", sql); + query.ToList(); + + //���û�е������ԣ��򵥶������ + query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b WHERE (b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'typeTitle')", sql); + query.ToList(); + + query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b WHERE (b.\"name\" = 'typeTitle' AND b.\"guid\" = a.\"typeguid\")", sql); + query.ToList(); + + query = select.Where((a, b, c) => c.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeparentinfo\" c WHERE (c.\"name\" = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .Where(a => a.Id == 10 && c.Name == "xxx") + .Where(a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b, \"testtypeparentinfo\" c WHERE (a.\"id\" = 10 AND c.\"name\" = 'xxx') AND (b.\"parentid\" = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.Where("a.\"clicks\" > 100 and a.\"id\" = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"clicks\" > 100 and a.\"id\" = @id)", sql); + query.ToList(); + } + [Fact] + public void WhereIf() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.WhereIf(true, a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"id\" = 10)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE ((a.\"id\" = 10 AND a.\"id\" > 10 OR a.\"clicks\" > 100))", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"id\" = 10) AND (a.\"clicks\" > 100)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" WHERE (a__Type.\"name\" = 'typeTitle')", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" WHERE (a__Type.\"name\" = 'typeTitle' AND a__Type.\"guid\" = a.\"typeguid\")", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a LEFT JOIN \"testtypeinfo\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfo\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"name\" = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(true, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b, \"testtypeparentinfo\" c WHERE (a.\"id\" = 10 AND c.\"name\" = 'xxx') AND (b.\"parentid\" = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(true, "a.\"clicks\" > 100 and a.\"id\" = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a WHERE (a.\"clicks\" > 100 and a.\"id\" = @id)", sql); + query.ToList(); + + // ==========================================WhereIf(false) + + //����е�������a.Type��a.Type.Parent ���ǵ������� + query = select.WhereIf(false, a => a.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + query2 = select.From((s, b, c) => s + .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(false, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a, \"testtypeinfo\" b, \"testtypeparentinfo\" c", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(false, "a.\"clicks\" > 100 and a.\"id\" = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topic\" a", sql); + query.ToList(); + } + [Fact] + public void WhereExists() + { + var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); + + sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + + //.Offset(a.Id) + + .Any() + ).Any() + ).ToList(); + } + [Fact] + public void GroupBy() + { + var groupby = select.From((s, b, c) => s + .Where(a => a.Id == 1) + ) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()) + .Offset(10) + .Limit(2) + .ToList(a => new + { + a.Key.tt2, + cou1 = a.Count(), + arg1 = a.Avg(a.Key.mod4), + ccc2 = a.Key.tt2 ?? "now()", + //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") + ccc3 = a.Max(a.Value.Item3.Id) + }); + + var testpid1 = g.pgsql.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); + g.pgsql.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); + + var aggsql1 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist1 = select + .GroupBy(a => a.Title) + .ToList(b => new + { + b.Key, + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToSql(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToList(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql3 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid), + sum3 = b.Sum(b.Value.Type.Parent.Id) + }); + } + [Fact] + public void ToAggregate() + { + var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); + } + [Fact] + public void OrderBy() + { + var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); + } + [Fact] + public void Skip_Offset() + { + var sql = select.Offset(10).Limit(10).ToList(); + } + [Fact] + public void Take_Limit() + { + var sql = select.Limit(10).ToList(); + } + [Fact] + public void Page() + { + var sql1 = select.Page(1, 10).ToList(); + var sql2 = select.Page(2, 10).ToList(); + var sql3 = select.Page(3, 10).ToList(); + + var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); + var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); + var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); + } + [Fact] + public void Distinct() + { + var t1 = select.Distinct().ToList(a => a.Title); + var t2 = select.Distinct().Limit(10).ToList(a => a.Title); + } + + [Fact] + public void Sum() + { + } + [Fact] + public void Min() + { + } + [Fact] + public void Max() + { + } + [Fact] + public void Avg() + { + } + [Fact] + public void As() + { + } + + [Fact] + public void AsTable() + { + + var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); + + Func tableRule = (type, oldname) => + { + if (type == typeof(Topic)) return oldname + "AsTable1"; + else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; + return oldname + "AsTable"; + }; + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\"", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx'", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfoAsTable\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" b ON b.\"guid\" = a.\"typeguid\"", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" b ON b.\"guid\" = a.\"typeguid\" AND b.\"name\" = 'xxx'", sql); + + query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" AND a__Type.\"name\" = 'xxx' LEFT JOIN \"testtypeparentinfoAsTable\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\" WHERE (a__Type__Parent.\"id\" = 10)", sql); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfoAsTable\" a__Type__Parent ON a__Type__Parent.\"id\" = a__Type.\"parentid\"", sql); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a__Type.\"guid\", a__Type.\"parentid\", a__Type.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" a__Type ON a__Type.\"guid\" = a.\"typeguid\" LEFT JOIN \"testtypeparentinfoAsTable\" c ON c.\"id\" = a__Type.\"parentid\"", sql); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", b.\"guid\", b.\"parentid\", b.\"name\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfoAsTable2\" b ON a.\"typeguid\" = b.\"guid\" LEFT JOIN \"testtypeparentinfoAsTable\" c ON b.\"parentid\" = c.\"id\"", sql); + + //������϶����㲻�� + query = select.LeftJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\"", sql); + + query = select.LeftJoin("\"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", new { bname = "xxx" }).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"id\", a.\"clicks\", a.\"typeguid\", a.\"title\", a.\"createtime\" FROM \"tb_topicAsTable1\" a LEFT JOIN \"testtypeinfo\" b on b.\"guid\" = a.\"typeguid\" and b.\"name\" = @bname", sql); + } + + public class TestInclude_OneToManyModel1 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public virtual TestInclude_OneToManyModel2 model2 { get; set; } + + public string m1name { get; set; } + } + public class TestInclude_OneToManyModel2 + { + [Column(IsPrimary = true)] + public int model2id { get; set; } + public virtual TestInclude_OneToManyModel1 model1 { get; set; } + + public string m2setting { get; set; } + + public List childs { get; set; } + } + public class TestInclude_OneToManyModel3 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model2111Idaaa { get; set; } + public string title { get; set; } + + public List childs2 { get; set; } + } + public class TestInclude_OneToManyModel4 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model3333Id333 { get; set; } + public string title444 { get; set; } + } + + [Fact] + public void Include_OneToMany() + { + var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; + model1.id = (int)g.pgsql.Insert(model1).ExecuteIdentity(); + var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; + g.pgsql.Insert(model2).ExecuteAffrows(); + + var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; + model3_1.id = (int)g.pgsql.Insert(model3_1).ExecuteIdentity(); + var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; + model3_2.id = (int)g.pgsql.Insert(model3_2).ExecuteIdentity(); + var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; + model3_3.id = (int)g.pgsql.Insert(model3_2).ExecuteIdentity(); + + var model4s = new[] { + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } + }; + Assert.Equal(5, g.pgsql.Insert(model4s).ExecuteAffrows()); + + var t0 = g.pgsql.Select() + .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t1 = g.pgsql.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t2 = g.pgsql.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + + var t00 = g.pgsql.Select() + .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t11 = g.pgsql.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t22 = g.pgsql.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + } + + public class TestInclude_OneToManyModel11 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2id { get; set; } + public string m3setting { get; set; } + public TestInclude_OneToManyModel22 model2 { get; set; } + public string m1name { get; set; } + } + + public class TestInclude_OneToManyModel22 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public string m2setting { get; set; } + public List childs { get; set; } + } + public class TestInclude_OneToManyModel33 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2Id { get; set; } + public string title { get; set; } + public string setting { get; set; } + } + [Fact] + public void Include_OneToMany2() + { + string setting = "x"; + var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; + model2.id = (int)g.pgsql.Insert(model2).ExecuteIdentity(); + + var model3s = new[] + { + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} + }; + Assert.Equal(3, g.pgsql.Insert(model3s).ExecuteAffrows()); + + var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; + model1.id = (int)g.pgsql.Insert(model1).ExecuteIdentity(); + + var t1 = g.pgsql.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + + var t11 = g.pgsql.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + } + + [Fact] + public void Include_OneToChilds() + { + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_中国" + }; + tag1.Id = (int)g.pgsql.Insert(tag1).ExecuteIdentity(); + var tag1_1 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_北京" + }; + tag1_1.Id = (int)g.pgsql.Insert(tag1_1).ExecuteIdentity(); + var tag1_2 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_上海" + }; + tag1_2.Id = (int)g.pgsql.Insert(tag1_2).ExecuteIdentity(); + + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_美国" + }; + tag2.Id = (int)g.pgsql.Insert(tag2).ExecuteIdentity(); + var tag2_1 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_纽约" + }; + tag2_1.Id = (int)g.pgsql.Insert(tag2_1).ExecuteIdentity(); + var tag2_2 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_华盛顿" + }; + tag2_2.Id = (int)g.pgsql.Insert(tag2_2).ExecuteIdentity(); + + var tags0 = g.pgsql.Select() + .Include(a => a.Parent) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags1 = g.pgsql.Select() + .IncludeMany(a => a.Tags) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags2 = g.pgsql.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags3 = g.pgsql.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags11 = g.pgsql.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags22 = g.pgsql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags33 = g.pgsql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + } + + [Fact] + public void Include_ManyToMany() + { + + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_01_中国" + }; + tag1.Id = (int)g.pgsql.Insert(tag1).ExecuteIdentity(); + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_02_美国" + }; + tag2.Id = (int)g.pgsql.Insert(tag2).ExecuteIdentity(); + var tag3 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_03_日本" + }; + tag3.Id = (int)g.pgsql.Insert(tag3).ExecuteIdentity(); + + var song1 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_01_我是中国人.mp3", + Url = "http://ww.baidu.com/" + }; + song1.Id = (int)g.pgsql.Insert(song1).ExecuteIdentity(); + var song2 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_02_爱你一万年.mp3", + Url = "http://ww.163.com/" + }; + song2.Id = (int)g.pgsql.Insert(song2).ExecuteIdentity(); + var song3 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_03_千年等一回.mp3", + Url = "http://ww.sina.com/" + }; + song3.Id = (int)g.pgsql.Insert(song3).ExecuteIdentity(); + + g.pgsql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.pgsql.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.pgsql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.pgsql.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.pgsql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.pgsql.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); + + var songs1 = g.pgsql.Select() + .IncludeMany(a => a.Tags) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs1.Count); + Assert.Equal(2, songs1[0].Tags.Count); + Assert.Equal(1, songs1[1].Tags.Count); + Assert.Equal(3, songs1[2].Tags.Count); + + var songs2 = g.pgsql.Select() + .IncludeMany(a => a.Tags, + then => then.IncludeMany(t => t.Songs)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs2.Count); + Assert.Equal(2, songs2[0].Tags.Count); + Assert.Equal(1, songs2[1].Tags.Count); + Assert.Equal(3, songs2[2].Tags.Count); + + var tags3 = g.pgsql.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + + + var songs11 = g.pgsql.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs11.Count); + Assert.Equal(1, songs11[0].Tags.Count); + Assert.Equal(1, songs11[1].Tags.Count); + Assert.Equal(1, songs11[2].Tags.Count); + + var songs22 = g.pgsql.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.IncludeMany(t => t.Songs.Take(1))) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs22.Count); + Assert.Equal(1, songs22[0].Tags.Count); + Assert.Equal(1, songs22[1].Tags.Count); + Assert.Equal(1, songs22[2].Tags.Count); + + var tags33 = g.pgsql.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs.Take(1)) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLUpdateTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLUpdateTest.cs index d1e96cc0..8d26b835 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLUpdateTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/Curd/PostgreSQLUpdateTest.cs @@ -3,125 +3,139 @@ using System; using System.Collections.Generic; using Xunit; -namespace FreeSql.Tests.PostgreSQL { - public class PostgreSQLUpdateTest { - IUpdate update => g.pgsql.Update(); +namespace FreeSql.Tests.PostgreSQL +{ + public class PostgreSQLUpdateTest + { + IUpdate update => g.pgsql.Update(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - - [Fact] - public void Dywhere() { - Assert.Null(g.pgsql.Update().ToSql()); - Assert.Equal("UPDATE \"tb_topic\" SET title='test' \r\nWHERE (\"id\" = 1 OR \"id\" = 2)", g.pgsql.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); - Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"id\" = 1)", g.pgsql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"id\" = 1 OR \"id\" = 2)", g.pgsql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"id\" = 1)", g.pgsql.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); - } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void SetSource() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = @p_0, \"title\" = @p_1, \"createtime\" = @p_2 WHERE (\"id\" = 1)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(g.pgsql.Update().ToSql()); + Assert.Equal("UPDATE \"tb_topic\" SET title='test' \r\nWHERE (\"id\" = 1 OR \"id\" = 2)", g.pgsql.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); + Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"id\" = 1)", g.pgsql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"id\" = 1 OR \"id\" = 2)", g.pgsql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"id\" = 1)", g.pgsql.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); + } - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + [Fact] + public void SetSource() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = @p_0, \"title\" = @p_1, \"createtime\" = @p_2 WHERE (\"id\" = 1)", sql); - sql = update.SetSource(items).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = CASE \"id\" WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, \"title\" = CASE \"id\" WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, \"createtime\" = CASE \"id\" WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = CASE \"id\" WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = CASE \"id\" WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, \"title\" = CASE \"id\" WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, \"createtime\" = CASE \"id\" WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020,1,1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"createtime\" = @p_0 WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void IgnoreColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = @p_0 WHERE (\"id\" = 1)", sql); - } - [Fact] - public void UpdateColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = @p_0 WHERE (\"id\" = 1)", sql); - } - [Fact] - public void Set() { - var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = @p_0 WHERE (\"id\" = 1)", sql); + sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = CASE \"id\" WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = @p_0, \"createtime\" = @p_1 WHERE (\"id\" = 1)", sql); + sql = update.SetSource(items).Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"createtime\" = @p_0 WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void IgnoreColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = @p_0 WHERE (\"id\" = 1)", sql); + } + [Fact] + public void UpdateColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = @p_0 WHERE (\"id\" = 1)", sql); + } + [Fact] + public void Set() + { + var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = @p_0 WHERE (\"id\" = 1)", sql); - sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = coalesce(\"clicks\", 0) * 10 / 1 WHERE (\"id\" = 1)", sql); + sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"title\" = @p_0, \"createtime\" = @p_1 WHERE (\"id\" = 1)", sql); - sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"id\" = (\"id\" - 10) WHERE (\"id\" = 1)", sql); + sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = coalesce(\"clicks\", 0) * 10 / 1 WHERE (\"id\" = 1)", sql); - int incrv = 10; - sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = coalesce(\"clicks\", 0) * 10 / 1 WHERE (\"id\" = 1)", sql); + sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"id\" = (\"id\" - 10) WHERE (\"id\" = 1)", sql); - sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"id\" = (\"id\" - 10) WHERE (\"id\" = 1)", sql); + int incrv = 10; + sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = coalesce(\"clicks\", 0) * 10 / 1 WHERE (\"id\" = 1)", sql); - sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = \"clicks\" * 10 / 1 WHERE (\"id\" = 1)", sql); + sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"id\" = (\"id\" - 10) WHERE (\"id\" = 1)", sql); - sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"id\" = 10 WHERE (\"id\" = 1)", sql); - } - [Fact] - public void SetRaw() { - var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + @incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET clicks = clicks + @incrClick WHERE (\"id\" = 1)", sql); - } - [Fact] - public void Where() { - var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"id\" = 1)", sql); + sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"clicks\" = \"clicks\" * 10 / 1 WHERE (\"id\" = 1)", sql); - sql = update.Where("id = @id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (id = @id)", sql); + sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"id\" = 10 WHERE (\"id\" = 1)", sql); + } + [Fact] + public void SetRaw() + { + var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + @incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET clicks = clicks + @incrClick WHERE (\"id\" = 1)", sql); + } + [Fact] + public void Where() + { + var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"id\" = 1)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"id\" = 1)", sql); + sql = update.Where("id = @id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (id = @id)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"id\" = 1)", sql); - } - [Fact] - public void ExecuteAffrows() { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteUpdated() { + } + [Fact] + public void ExecuteAffrows() + { - } + } + [Fact] + public void ExecuteUpdated() + { - [Fact] - public void AsTable() { - Assert.Null(g.pgsql.Update().ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test' \r\nWHERE (\"id\" = 1 OR \"id\" = 2)", g.pgsql.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"id\" = 1)", g.pgsql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"id\" = 1 OR \"id\" = 2)", g.pgsql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"id\" = 1)", g.pgsql.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - } - } + } + + [Fact] + public void AsTable() + { + Assert.Null(g.pgsql.Update().ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test' \r\nWHERE (\"id\" = 1 OR \"id\" = 2)", g.pgsql.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"id\" = 1)", g.pgsql.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"id\" = 1 OR \"id\" = 2)", g.pgsql.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"id\" = 1)", g.pgsql.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/BoolNullableTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/BoolNullableTest.cs index 564d592c..73804ba1 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/BoolNullableTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/BoolNullableTest.cs @@ -2,1561 +2,1595 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.PostgreSQLMapType { - public class BoolNullableTest { - class BoolNullableMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool))] - public bool? tobool { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool? tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool? tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool? toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool? toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool? toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool? tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool? tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool? tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool? tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool? tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool? toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool? toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool? touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool? touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool? toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool? toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool? tostring { get; set; } = true; - } - [Fact] - public void Bool() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item = new BoolNullableMap { tobool = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item = new BoolNullableMap { tobool = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update all - item.tobool = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item.tobool = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item.tobool = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item = new BoolNullableMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item = new BoolNullableMap { tosbyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item.tosbyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item.tosbytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item = new BoolNullableMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item = new BoolNullableMap { toshort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item.toshort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item.toshortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item = new BoolNullableMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item = new BoolNullableMap { toint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item.toint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item = new BoolNullableMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item = new BoolNullableMap { tointnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item.tointnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item = new BoolNullableMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item = new BoolNullableMap { tolong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item.tolong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item.tolongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item = new BoolNullableMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item = new BoolNullableMap { tobyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item.tobyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item.tobytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item = new BoolNullableMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item = new BoolNullableMap { toushort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item.toushort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item.toushortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item = new BoolNullableMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item = new BoolNullableMap { touint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item.touint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item = new BoolNullableMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item = new BoolNullableMap { touintnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item.touintnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item = new BoolNullableMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item = new BoolNullableMap { toulong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item.toulong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item.toulongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.pgsql; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item = new BoolNullableMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item = new BoolNullableMap { tostring = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item.tostring = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.PostgreSQLMapType +{ + public class BoolNullableTest + { + class BoolNullableMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool))] + public bool? tobool { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool? tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool? tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool? toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool? toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool? toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool? tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool? tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool? tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool? tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool? tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool? toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool? toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool? touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool? touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool? toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool? toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool? tostring { get; set; } = true; + } + [Fact] + public void Bool() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item = new BoolNullableMap { tobool = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item = new BoolNullableMap { tobool = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update all + item.tobool = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item.tobool = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item.tobool = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item = new BoolNullableMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item = new BoolNullableMap { tosbyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item.tosbyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item.tosbytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item = new BoolNullableMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item = new BoolNullableMap { toshort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item.toshort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item.toshortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item = new BoolNullableMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item = new BoolNullableMap { toint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item.toint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item = new BoolNullableMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item = new BoolNullableMap { tointnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item.tointnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item = new BoolNullableMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item = new BoolNullableMap { tolong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item.tolong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item.tolongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item = new BoolNullableMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item = new BoolNullableMap { tobyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item.tobyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item.tobytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item = new BoolNullableMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item = new BoolNullableMap { toushort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item.toushort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item.toushortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item = new BoolNullableMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item = new BoolNullableMap { touint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item.touint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item = new BoolNullableMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item = new BoolNullableMap { touintnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item.touintnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item = new BoolNullableMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item = new BoolNullableMap { toulong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item.toulong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item.toulongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.pgsql; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item = new BoolNullableMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item = new BoolNullableMap { tostring = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item.tostring = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/BoolTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/BoolTest.cs index 23d48807..37ce2ca4 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/BoolTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/BoolTest.cs @@ -2,1095 +2,1129 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.PostgreSQLMapType { - public class BoolTest { - - class BoolMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool?))] - public bool toboolnullable { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool tostring { get; set; } = true; - } - - [Fact] - public void BoolNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item = new BoolMap { toboolnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update all - item.toboolnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item.toboolnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toboolnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toboolnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item = new BoolMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item = new BoolMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item = new BoolMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item = new BoolMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item = new BoolMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item = new BoolMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item = new BoolMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item = new BoolMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item = new BoolMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item = new BoolMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item = new BoolMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item = new BoolMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item = new BoolMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item = new BoolMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item = new BoolMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item = new BoolMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.pgsql; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item = new BoolMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.PostgreSQLMapType +{ + public class BoolTest + { + + class BoolMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool?))] + public bool toboolnullable { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool tostring { get; set; } = true; + } + + [Fact] + public void BoolNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item = new BoolMap { toboolnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update all + item.toboolnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item.toboolnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toboolnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toboolnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item = new BoolMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item = new BoolMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item = new BoolMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item = new BoolMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item = new BoolMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item = new BoolMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item = new BoolMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item = new BoolMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item = new BoolMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item = new BoolMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item = new BoolMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item = new BoolMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item = new BoolMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item = new BoolMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item = new BoolMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item = new BoolMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.pgsql; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item = new BoolMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/EnumTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/EnumTest.cs index 05e7d229..8ecd87a7 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/EnumTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/EnumTest.cs @@ -3,252 +3,259 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.PostgreSQLMapType { - public class EnumTest { - class EnumTestMap { - public Guid id { get; set; } +namespace FreeSql.Tests.PostgreSQLMapType +{ + public class EnumTest + { + class EnumTestMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(int))] - public ToStringMapEnum enum_to_int { get; set; } - [Column(MapType = typeof(int?))] - public ToStringMapEnum? enumnullable_to_int { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void EnumToString() { - //insert - var orm = g.pgsql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(int))] + public ToStringMapEnum enum_to_int { get; set; } + [Column(MapType = typeof(int?))] + public ToStringMapEnum? enumnullable_to_int { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void EnumToString() + { + //insert + var orm = g.pgsql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToString() { - //insert - var orm = g.pgsql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToString() + { + //insert + var orm = g.pgsql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void EnumToInt() { - //insert - var orm = g.pgsql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + [Fact] + public void EnumToInt() + { + //insert + var orm = g.pgsql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //update all - item.enum_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update all + item.enum_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - item.enum_to_int = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + item.enum_to_int = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToInt() { - //insert - var orm = g.pgsql; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToInt() + { + //insert + var orm = g.pgsql; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); + item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); - //update all - item.enumnullable_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); + //update all + item.enumnullable_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); - item.enumnullable_to_int = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + item.enumnullable_to_int = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/JTokenTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/JTokenTest.cs index ec3f4465..6a8fb1cf 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/JTokenTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/JTokenTest.cs @@ -4,421 +4,431 @@ using System; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQLMapType { - public class JTokenTest { - class JTokenTestMap { - public Guid id { get; set; } +namespace FreeSql.Tests.PostgreSQLMapType +{ + public class JTokenTest + { + class JTokenTestMap + { + public Guid id { get; set; } - [Column(MapType = typeof(JToken))] - public string string_to_jtoken { get; set; } - [Column(MapType = typeof(JArray))] - public string string_to_jarray { get; set; } - [Column(MapType = typeof(JObject))] - public string string_to_jobject { get; set; } + [Column(MapType = typeof(JToken))] + public string string_to_jtoken { get; set; } + [Column(MapType = typeof(JArray))] + public string string_to_jarray { get; set; } + [Column(MapType = typeof(JObject))] + public string string_to_jobject { get; set; } - [Column(MapType = typeof(string))] - public JToken jtoken_to_string { get; set; } - [Column(MapType = typeof(string))] - public JArray jarray_to_string { get; set; } - [Column(MapType = typeof(string))] - public JObject jobject_to_string { get; set; } - } - [Fact] - public void JTokenWithObjectToString() { - //insert - var orm = g.pgsql; - var item = new JTokenTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jtoken_to_string); + [Column(MapType = typeof(string))] + public JToken jtoken_to_string { get; set; } + [Column(MapType = typeof(string))] + public JArray jarray_to_string { get; set; } + [Column(MapType = typeof(string))] + public JObject jobject_to_string { get; set; } + } + [Fact] + public void JTokenWithObjectToString() + { + //insert + var orm = g.pgsql; + var item = new JTokenTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jtoken_to_string); - var json = JToken.FromObject(new { test1 = 1, test2 = "222" }); - item = new JTokenTestMap { jtoken_to_string = json }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jtoken_to_string); + var json = JToken.FromObject(new { test1 = 1, test2 = "222" }); + item = new JTokenTestMap { jtoken_to_string = json }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jtoken_to_string); - //update - json = JToken.FromObject(new { test2 = 33, test3 = "333" }); - item.jtoken_to_string = json; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jtoken_to_string); + //update + json = JToken.FromObject(new { test2 = 33, test3 = "333" }); + item.jtoken_to_string = json; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jtoken_to_string); - item.jtoken_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == json).First()); - find = orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jtoken_to_string); + item.jtoken_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == json).First()); + find = orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jtoken_to_string); - //update set - json = JToken.FromObject(new { testa = 455, test31 = "666" }); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jtoken_to_string, json).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jtoken_to_string); + //update set + json = JToken.FromObject(new { testa = 455, test31 = "666" }); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jtoken_to_string, json).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jtoken_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jtoken_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == json).First()); - find = orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jtoken_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jtoken_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == json).First()); + find = orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jtoken_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.jtoken_to_string == json).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.jtoken_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void JTokenWithArrayToString() { - //insert - var orm = g.pgsql; - var item = new JTokenTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jtoken_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.jtoken_to_string == json).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.jtoken_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void JTokenWithArrayToString() + { + //insert + var orm = g.pgsql; + var item = new JTokenTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jtoken_to_string); - var json = JArray.FromObject(new[] { "a", "b" }); - item = new JTokenTestMap { jtoken_to_string = json }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jtoken_to_string); + var json = JArray.FromObject(new[] { "a", "b" }); + item = new JTokenTestMap { jtoken_to_string = json }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jtoken_to_string); - //update - json = JArray.FromObject(new[] { "333", "zzz" }); - item.jtoken_to_string = json; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jtoken_to_string); + //update + json = JArray.FromObject(new[] { "333", "zzz" }); + item.jtoken_to_string = json; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jtoken_to_string); - item.jtoken_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == json).First()); - find = orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jtoken_to_string); + item.jtoken_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == json).First()); + find = orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jtoken_to_string); - //update set - json = JArray.FromObject(new[] { "zxzz", "sdfsdf" }); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jtoken_to_string, json).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jtoken_to_string); + //update set + json = JArray.FromObject(new[] { "zxzz", "sdfsdf" }); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jtoken_to_string, json).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jtoken_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jtoken_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == json).First()); - find = orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jtoken_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jtoken_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == json).First()); + find = orm.Select().Where(a => a.id == item.id && a.jtoken_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jtoken_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.jtoken_to_string == json).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.jtoken_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.jtoken_to_string == json).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.jtoken_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void JArrayToString() { - //insert - var orm = g.pgsql; - var item = new JTokenTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jarray_to_string); + [Fact] + public void JArrayToString() + { + //insert + var orm = g.pgsql; + var item = new JTokenTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jarray_to_string); - var json = JArray.FromObject(new[] { "a", "b" }); - item = new JTokenTestMap { jarray_to_string = json }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jarray_to_string); + var json = JArray.FromObject(new[] { "a", "b" }); + item = new JTokenTestMap { jarray_to_string = json }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jarray_to_string); - //update - json = JArray.FromObject(new[] { "333", "zzz" }); - item.jarray_to_string = json; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jarray_to_string); + //update + json = JArray.FromObject(new[] { "333", "zzz" }); + item.jarray_to_string = json; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jarray_to_string); - item.jarray_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.jarray_to_string == json).First()); - find = orm.Select().Where(a => a.id == item.id && a.jarray_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jarray_to_string); + item.jarray_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.jarray_to_string == json).First()); + find = orm.Select().Where(a => a.id == item.id && a.jarray_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jarray_to_string); - //update set - json = JArray.FromObject(new[] { "zxzz", "sdfsdf" }); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jarray_to_string, json).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jarray_to_string); + //update set + json = JArray.FromObject(new[] { "zxzz", "sdfsdf" }); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jarray_to_string, json).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jarray_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jarray_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.jarray_to_string == json).First()); - find = orm.Select().Where(a => a.id == item.id && a.jarray_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jarray_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jarray_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.jarray_to_string == json).First()); + find = orm.Select().Where(a => a.id == item.id && a.jarray_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jarray_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.jarray_to_string == json).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.jarray_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void JObjectToString() { - //insert - var orm = g.pgsql; - var item = new JTokenTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jobject_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.jarray_to_string == json).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.jarray_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void JObjectToString() + { + //insert + var orm = g.pgsql; + var item = new JTokenTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jobject_to_string); - var json = JObject.FromObject(new { test1 = 1, test2 = "222" }); - item = new JTokenTestMap { jobject_to_string = json }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jobject_to_string); + var json = JObject.FromObject(new { test1 = 1, test2 = "222" }); + item = new JTokenTestMap { jobject_to_string = json }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jobject_to_string); - //update - json = JObject.FromObject(new { test2 = 33, test3 = "333" }); - item.jobject_to_string = json; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jobject_to_string); + //update + json = JObject.FromObject(new { test2 = 33, test3 = "333" }); + item.jobject_to_string = json; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jobject_to_string); - item.jobject_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.jobject_to_string == json).First()); - find = orm.Select().Where(a => a.id == item.id && a.jobject_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jobject_to_string); + item.jobject_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.jobject_to_string == json).First()); + find = orm.Select().Where(a => a.id == item.id && a.jobject_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jobject_to_string); - //update set - json = JObject.FromObject(new { testa = 455, test31 = "666" }); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jobject_to_string, json).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json, find.jobject_to_string); + //update set + json = JObject.FromObject(new { testa = 455, test31 = "666" }); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jobject_to_string, json).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json, find.jobject_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jobject_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.jobject_to_string == json).First()); - find = orm.Select().Where(a => a.id == item.id && a.jobject_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.jobject_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.jobject_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.jobject_to_string == json).First()); + find = orm.Select().Where(a => a.id == item.id && a.jobject_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.jobject_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.jobject_to_string == json).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.jobject_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.jobject_to_string == json).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.jobject_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void StringToJToken() { - //insert - var orm = g.pgsql; - var item = new JTokenTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jtoken); + [Fact] + public void StringToJToken() + { + //insert + var orm = g.pgsql; + var item = new JTokenTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jtoken); - var json = JToken.FromObject(new { test1 = 1, test2 = "222" }); - var whereJson = JToken.FromObject(new { test2 = "222" }); - item = new JTokenTestMap { string_to_jtoken = json.ToString() }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json["test2"], JToken.Parse(find.string_to_jtoken)["test2"]); + var json = JToken.FromObject(new { test1 = 1, test2 = "222" }); + var whereJson = JToken.FromObject(new { test2 = "222" }); + item = new JTokenTestMap { string_to_jtoken = json.ToString() }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json["test2"], JToken.Parse(find.string_to_jtoken)["test2"]); - //update - json = JToken.FromObject(new { test2 = 33, test3 = "333" }); - whereJson = JToken.FromObject(new { test3 = "333" }); - item.string_to_jtoken = json.ToString(); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json["test3"], JToken.Parse(find.string_to_jtoken)["test3"]); + //update + json = JToken.FromObject(new { test2 = 33, test3 = "333" }); + whereJson = JToken.FromObject(new { test3 = "333" }); + item.string_to_jtoken = json.ToString(); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json["test3"], JToken.Parse(find.string_to_jtoken)["test3"]); - item.string_to_jtoken = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First()); - find = orm.Select().Where(a => a.id == item.id && a.string_to_jtoken == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jtoken); + item.string_to_jtoken = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First()); + find = orm.Select().Where(a => a.id == item.id && a.string_to_jtoken == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jtoken); - //update set - json = JToken.FromObject(new { testa = 455, test31 = "666" }); - whereJson = JToken.FromObject(new { test31 = "666" }); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jtoken, json.ToString()).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json["test31"], JToken.Parse(find.string_to_jtoken)["test31"]); + //update set + json = JToken.FromObject(new { testa = 455, test31 = "666" }); + whereJson = JToken.FromObject(new { test31 = "666" }); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jtoken, json.ToString()).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json["test31"], JToken.Parse(find.string_to_jtoken)["test31"]); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jtoken, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First()); - find = orm.Select().Where(a => a.id == item.id && a.string_to_jtoken == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jtoken); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jtoken, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).First()); + find = orm.Select().Where(a => a.id == item.id && a.string_to_jtoken == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jtoken); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.string_to_jtoken == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void StringToJObject() { - //insert - var orm = g.pgsql; - var item = new JTokenTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jobject); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && JToken.Parse(a.string_to_jtoken).Contains(whereJson)).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.string_to_jtoken == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void StringToJObject() + { + //insert + var orm = g.pgsql; + var item = new JTokenTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jobject); - var json = JObject.FromObject(new { test1 = 1, test2 = "222" }); - item = new JTokenTestMap { string_to_jobject = json.ToString() }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test1")).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json["test2"], JObject.Parse(find.string_to_jobject)["test2"]); + var json = JObject.FromObject(new { test1 = 1, test2 = "222" }); + item = new JTokenTestMap { string_to_jobject = json.ToString() }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test1")).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json["test2"], JObject.Parse(find.string_to_jobject)["test2"]); - //update - json = JObject.FromObject(new { test2 = 33, test3 = "333" }); - item.string_to_jobject = json.ToString(); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test3")).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json["test3"], JObject.Parse(find.string_to_jobject)["test3"]); + //update + json = JObject.FromObject(new { test2 = 33, test3 = "333" }); + item.string_to_jobject = json.ToString(); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test3")).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json["test3"], JObject.Parse(find.string_to_jobject)["test3"]); - item.string_to_jobject = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test3")).First()); - find = orm.Select().Where(a => a.id == item.id && a.string_to_jobject == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jobject); + item.string_to_jobject = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test3")).First()); + find = orm.Select().Where(a => a.id == item.id && a.string_to_jobject == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jobject); - //update set - json = JObject.FromObject(new { testa = 455, test31 = "666" }); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jobject, json.ToString()).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test31")).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json["test31"], JObject.Parse(find.string_to_jobject)["test31"]); + //update set + json = JObject.FromObject(new { testa = 455, test31 = "666" }); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jobject, json.ToString()).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test31")).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json["test31"], JObject.Parse(find.string_to_jobject)["test31"]); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jobject, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test31")).First()); - find = orm.Select().Where(a => a.id == item.id && a.string_to_jobject == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jobject); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jobject, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test31")).First()); + find = orm.Select().Where(a => a.id == item.id && a.string_to_jobject == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jobject); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test31")).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.string_to_jobject == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void StringToJArray() { - //insert - var orm = g.pgsql; - var item = new JTokenTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jarray); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && JObject.Parse(a.string_to_jobject).ContainsKey("test31")).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.string_to_jobject == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void StringToJArray() + { + //insert + var orm = g.pgsql; + var item = new JTokenTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jarray); - var json = JArray.FromObject(new[] { "aa", "bb" }); - item = new JTokenTestMap { string_to_jarray = json.ToString() }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("bb")).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json[1], JArray.Parse(find.string_to_jarray)[1]); + var json = JArray.FromObject(new[] { "aa", "bb" }); + item = new JTokenTestMap { string_to_jarray = json.ToString() }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("bb")).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json[1], JArray.Parse(find.string_to_jarray)[1]); - //update - json = JArray.FromObject(new[] { "aa", "dddd" }); - item.string_to_jarray = json.ToString(); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("dddd")).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json[1], JArray.Parse(find.string_to_jarray)[1]); + //update + json = JArray.FromObject(new[] { "aa", "dddd" }); + item.string_to_jarray = json.ToString(); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("dddd")).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json[1], JArray.Parse(find.string_to_jarray)[1]); - item.string_to_jarray = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("dddd")).First()); - find = orm.Select().Where(a => a.id == item.id && a.string_to_jarray == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jarray); + item.string_to_jarray = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("dddd")).First()); + find = orm.Select().Where(a => a.id == item.id && a.string_to_jarray == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jarray); - //update set - json = JArray.FromObject(new[] { "aa", "bdfdfb" }); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jarray, json.ToString()).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("bdfdfb")).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(json[1], JArray.Parse(find.string_to_jarray)[1]); + //update set + json = JArray.FromObject(new[] { "aa", "bdfdfb" }); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jarray, json.ToString()).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("bdfdfb")).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(json[1], JArray.Parse(find.string_to_jarray)[1]); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jarray, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("bdfdfb")).First()); - find = orm.Select().Where(a => a.id == item.id && a.string_to_jarray == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.string_to_jarray); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.string_to_jarray, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("bdfdfb")).First()); + find = orm.Select().Where(a => a.id == item.id && a.string_to_jarray == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.string_to_jarray); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("bdfdfb")).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.string_to_jarray == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && JArray.Parse(a.string_to_jarray).Contains("bdfdfb")).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.string_to_jarray == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/ToStringTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/ToStringTest.cs index 814a7acf..56888345 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/ToStringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/MapType/ToStringTest.cs @@ -3,555 +3,568 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.PostgreSQLMapType { - public class ToStringTest { - class ToStringMap { - public Guid id { get; set; } +namespace FreeSql.Tests.PostgreSQLMapType +{ + public class ToStringTest + { + class ToStringMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan timespan_to_string { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan? timespannullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan timespan_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan? timespannullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime datetime_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime? datetimenullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime datetime_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime? datetimenullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid guid_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid? guidnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid guid_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid? guidnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger biginteger_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger? bigintegernullable_to_string { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void Enum1() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(string))] + public BigInteger biginteger_to_string { get; set; } + [Column(MapType = typeof(string))] + public BigInteger? bigintegernullable_to_string { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void Enum1() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullable() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullable() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigInteger1() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(0, find.biginteger_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigInteger1() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(0, find.biginteger_to_string); - item = new ToStringMap { biginteger_to_string = 100 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(100, find.biginteger_to_string); + item = new ToStringMap { biginteger_to_string = 100 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(100, find.biginteger_to_string); - //update all - item.biginteger_to_string = 200; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(200, find.biginteger_to_string); + //update all + item.biginteger_to_string = 200; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(200, find.biginteger_to_string); - item.biginteger_to_string = 205; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(205, find.biginteger_to_string); + item.biginteger_to_string = 205; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(205, find.biginteger_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(522, find.biginteger_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(522, find.biginteger_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(10005, find.biginteger_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(10005, find.biginteger_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigIntegerNullable() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigIntegerNullable() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - item = new ToStringMap { bigintegernullable_to_string = 101 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(101, find.bigintegernullable_to_string); + item = new ToStringMap { bigintegernullable_to_string = 101 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(101, find.bigintegernullable_to_string); - //update all - item.bigintegernullable_to_string = 2004; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(2004, find.bigintegernullable_to_string); + //update all + item.bigintegernullable_to_string = 2004; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(2004, find.bigintegernullable_to_string); - item.bigintegernullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + item.bigintegernullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(998, find.bigintegernullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(998, find.bigintegernullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.bigintegernullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.bigintegernullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpan1() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.Zero, find.timespan_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpan1() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.Zero, find.timespan_to_string); - item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); + item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); - //update all - item.timespan_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); + //update all + item.timespan_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpanNullable() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpanNullable() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); + item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); - //update all - item.timespannullable_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); + //update all + item.timespannullable_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); - item.timespannullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + item.timespannullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.timespannullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.timespannullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTime1() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.MinValue, find.datetime_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTime1() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.MinValue, find.datetime_to_string); - item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); + item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); - //update all - item.datetime_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); + //update all + item.datetime_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTimeNullable() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTimeNullable() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); + item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); - //update all - item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); + //update all + item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); - item.datetimenullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + item.datetimenullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.datetimenullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.datetimenullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void Guid1() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(Guid.Empty, find.guid_to_string); + [Fact] + public void Guid1() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(Guid.Empty, find.guid_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guid_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guid_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update all - newid = Guid.NewGuid(); - item.guid_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + //update all + newid = Guid.NewGuid(); + item.guid_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guid_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guid_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void GuidNullable() { - //insert - var orm = g.pgsql; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void GuidNullable() + { + //insert + var orm = g.pgsql; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guidnullable_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guidnullable_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - //update all - newid = Guid.NewGuid(); - item.guidnullable_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + //update all + newid = Guid.NewGuid(); + item.guidnullable_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - item.guidnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + item.guidnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guidnullable_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guidnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.guidnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.guidnullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLAdo/PostgreSQLAdoTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLAdo/PostgreSQLAdoTest.cs index a2da682d..7d8f4d28 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLAdo/PostgreSQLAdoTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLAdo/PostgreSQLAdoTest.cs @@ -2,56 +2,67 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.PostgreSQL { - public class PostgreSQLAdoTest { - [Fact] - public void Pool() { - var t1 = g.pgsql.Ado.MasterPool.StatisticsFullily; - } +namespace FreeSql.Tests.PostgreSQL +{ + public class PostgreSQLAdoTest + { + [Fact] + public void Pool() + { + var t1 = g.pgsql.Ado.MasterPool.StatisticsFullily; + } - [Fact] - public void SlavePools() { - var t2 = g.pgsql.Ado.SlavePools.Count; - } + [Fact] + public void SlavePools() + { + var t2 = g.pgsql.Ado.SlavePools.Count; + } - [Fact] - public void ExecuteReader() { - - } - [Fact] - public void ExecuteArray() { - - } - [Fact] - public void ExecuteNonQuery() { - - } - [Fact] - public void ExecuteScalar() { - - } + [Fact] + public void ExecuteReader() + { - [Fact] - public void Query() { + } + [Fact] + public void ExecuteArray() + { - g.pgsql.CodeFirst.SyncStructure(); - var t3 = g.pgsql.Ado.Query("select * from xxx"); + } + [Fact] + public void ExecuteNonQuery() + { - var t4 = g.pgsql.Ado.Query<(int, string, string)>("select * from xxx"); + } + [Fact] + public void ExecuteScalar() + { - var t5 = g.pgsql.Ado.Query("select * from xxx"); - } + } - [Fact] - public void QueryMultipline() { - g.pgsql.CodeFirst.SyncStructure(); - var t3 = g.pgsql.Ado.Query("select * from xxx; select * from xxx; select * from xxx"); - } + [Fact] + public void Query() + { - class xxx { - public int Id { get; set; } - public string Path { get; set; } - public string Title2 { get; set; } - } - } + g.pgsql.CodeFirst.SyncStructure(); + var t3 = g.pgsql.Ado.Query("select * from xxx"); + + var t4 = g.pgsql.Ado.Query<(int, string, string)>("select * from xxx"); + + var t5 = g.pgsql.Ado.Query("select * from xxx"); + } + + [Fact] + public void QueryMultipline() + { + g.pgsql.CodeFirst.SyncStructure(); + var t3 = g.pgsql.Ado.Query("select * from xxx; select * from xxx; select * from xxx"); + } + + class xxx + { + public int Id { get; set; } + public string Path { get; set; } + public string Title2 { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLCodeFirstTest.cs index 423dd33c..d8471901 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLCodeFirstTest.cs @@ -13,491 +13,504 @@ using System.Net.NetworkInformation; using System.Text; using Xunit; -namespace FreeSql.Tests.PostgreSQL { - public class PostgreSQLCodeFirstTest { +namespace FreeSql.Tests.PostgreSQL +{ + public class PostgreSQLCodeFirstTest + { - [Fact] - public void ı_ֶ() { - var sql = g.pgsql.CodeFirst.GetComparisonDDLStatements<ı>(); - g.pgsql.CodeFirst.SyncStructure<ı>(); + [Fact] + public void ı_ֶ() + { + var sql = g.pgsql.CodeFirst.GetComparisonDDLStatements<ı>(); + g.pgsql.CodeFirst.SyncStructure<ı>(); - var item = new ı { - = "Ա", - ʱ = DateTime.Now - }; - Assert.Equal(1, g.pgsql.Insert<ı>().AppendData(item).ExecuteAffrows()); - Assert.NotEqual(Guid.Empty, item.); - var item2 = g.pgsql.Select<ı>().Where(a => a. == item.).First(); - Assert.NotNull(item2); - Assert.Equal(item., item2.); - Assert.Equal(item., item2.); - } - class ı { - [Column(IsPrimary = true)] - public Guid { get; set; } + var item = new ı + { + = "Ա", + ʱ = DateTime.Now + }; + Assert.Equal(1, g.pgsql.Insert<ı>().AppendData(item).ExecuteAffrows()); + Assert.NotEqual(Guid.Empty, item.); + var item2 = g.pgsql.Select<ı>().Where(a => a. == item.).First(); + Assert.NotNull(item2); + Assert.Equal(item., item2.); + Assert.Equal(item., item2.); + } + class ı + { + [Column(IsPrimary = true)] + public Guid { get; set; } - public string { get; set; } + public string { get; set; } - public DateTime ʱ { get; set; } - } + public DateTime ʱ { get; set; } + } - [Fact] - public void AddUniques() { - var sql = g.pgsql.CodeFirst.GetComparisonDDLStatements(); - g.pgsql.CodeFirst.SyncStructure(); - } - [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] - class AddUniquesInfo { - public Guid id { get; set; } - [Column(Unique = "uk_phone")] - public string phone { get; set; } + [Fact] + public void AddUniques() + { + var sql = g.pgsql.CodeFirst.GetComparisonDDLStatements(); + g.pgsql.CodeFirst.SyncStructure(); + } + [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] + class AddUniquesInfo + { + public Guid id { get; set; } + [Column(Unique = "uk_phone")] + public string phone { get; set; } - [Column(Unique = "uk_group_index, uk_group_index22")] - public string group { get; set; } - [Column(Unique = "uk_group_index")] - public int index { get; set; } - [Column(Unique = "uk_group_index22")] - public string index22 { get; set; } - } + [Column(Unique = "uk_group_index, uk_group_index22")] + public string group { get; set; } + [Column(Unique = "uk_group_index")] + public int index { get; set; } + [Column(Unique = "uk_group_index22")] + public string index22 { get; set; } + } - [Fact] - public void AddField() { - var sql = g.pgsql.CodeFirst.GetComparisonDDLStatements(); - g.pgsql.Select(); + [Fact] + public void AddField() + { + var sql = g.pgsql.CodeFirst.GetComparisonDDLStatements(); + g.pgsql.Select(); - var id = g.pgsql.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); - } + var id = g.pgsql.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); + } - [Table(Name = "ccc.TopicAddField", OldName = "TopicAddField")] - public class TopicAddField { - [Column(IsIdentity = true)] - public int Id { get; set; } + [Table(Name = "ccc.TopicAddField", OldName = "TopicAddField")] + public class TopicAddField + { + [Column(IsIdentity = true)] + public int Id { get; set; } - public string name { get; set; } = "xxx"; + public string name { get; set; } = "xxx"; - public int clicks { get; set; } = 10; - //public int name { get; set; } = 3000; + public int clicks { get; set; } = 10; + //public int name { get; set; } = 3000; - //[Column(DbType = "varchar(200) not null", OldName = "title")] - //public string title222 { get; set; } = "333"; + //[Column(DbType = "varchar(200) not null", OldName = "title")] + //public string title222 { get; set; } = "333"; - //[Column(DbType = "varchar(200) not null")] - //public string title222333 { get; set; } = "xxx"; + //[Column(DbType = "varchar(200) not null")] + //public string title222333 { get; set; } = "xxx"; - //[Column(DbType = "varchar(100) not null", OldName = "title122333aaa")] - //public string titleaaa { get; set; } = "fsdf"; + //[Column(DbType = "varchar(100) not null", OldName = "title122333aaa")] + //public string titleaaa { get; set; } = "fsdf"; - [Column(IsIgnore = true)] - public DateTime ct { get; set; } = DateTime.Now; - } + [Column(IsIgnore = true)] + public DateTime ct { get; set; } = DateTime.Now; + } - [Fact] - public void GetComparisonDDLStatements() { + [Fact] + public void GetComparisonDDLStatements() + { - var sql = g.pgsql.CodeFirst.GetComparisonDDLStatements(); - g.pgsql.Select(); - } + var sql = g.pgsql.CodeFirst.GetComparisonDDLStatements(); + g.pgsql.Select(); + } - IInsert insert => g.pgsql.Insert(); - ISelect select => g.pgsql.Select(); + IInsert insert => g.pgsql.Insert(); + ISelect select => g.pgsql.Select(); - [Fact] - public void CurdAllField() { - NpgsqlConnection.GlobalTypeMapper.UseLegacyPostgis(); + [Fact] + public void CurdAllField() + { + NpgsqlConnection.GlobalTypeMapper.UseLegacyPostgis(); - var sql1 = select.Where(a => a.testFieldIntArray.Contains(1)).ToSql(); - var sql2 = select.Where(a => a.testFieldIntArray.Contains(1)).ToSql(); + var sql1 = select.Where(a => a.testFieldIntArray.Contains(1)).ToSql(); + var sql2 = select.Where(a => a.testFieldIntArray.Contains(1)).ToSql(); - var item = new TableAllType { }; - item.Id = (int)insert.AppendData(item).ExecuteIdentity(); + var item = new TableAllType { }; + item.Id = (int)insert.AppendData(item).ExecuteIdentity(); - var newitem = select.Where(a => a.Id == item.Id).ToOne(); + var newitem = select.Where(a => a.Id == item.Id).ToOne(); - var item2 = new TableAllType { - testFieldBitArray = new BitArray(Encoding.UTF8.GetBytes("")), - testFieldBitArrayArray = new[] { new BitArray(Encoding.UTF8.GetBytes("й")), new BitArray(Encoding.UTF8.GetBytes("")) }, - testFieldBool = true, - testFieldBoolArray = new[] { true, true, false, false }, - testFieldBoolArrayNullable = new bool?[] { true, true, null, false, false }, - testFieldBoolNullable = true, - testFieldByte = byte.MaxValue, - testFieldByteArray = new byte[] { 0, 1, 2, 3, 4, 5, 6 }, - testFieldByteArrayNullable = new byte?[] { 0, 1, 2, 3, null, 4, 5, 6 }, - testFieldByteNullable = byte.MinValue, - testFieldBytes = Encoding.UTF8.GetBytes("й"), - testFieldBytesArray = new[] { Encoding.UTF8.GetBytes("й"), Encoding.UTF8.GetBytes("й") }, - testFieldCidr = (IPAddress.Parse("10.0.0.0"), 8), - testFieldCidrArray = new[] { (IPAddress.Parse("10.0.0.0"), 8), (IPAddress.Parse("192.168.0.0"), 16) }, - testFieldCidrArrayNullable = new (IPAddress, int)?[] { (IPAddress.Parse("10.0.0.0"), 8), null, (IPAddress.Parse("192.168.0.0"), 16) }, - testFieldCidrNullable = (IPAddress.Parse("192.168.0.0"), 16), - testFieldDateTime = DateTime.Now, - testFieldDateTimeArray = new[] { DateTime.Now, DateTime.Now.AddHours(2) }, - testFieldDateTimeArrayNullable = new DateTime?[] { DateTime.Now, null, DateTime.Now.AddHours(2) }, - testFieldDateTimeNullable = DateTime.Now.AddDays(-1), - testFieldDecimal = 999.99M, - testFieldDecimalArray = new[] { 999.91M, 999.92M, 999.93M }, - testFieldDecimalArrayNullable = new decimal?[] { 998.11M, 998.12M, 998.13M }, - testFieldDecimalNullable = 111.11M, - testFieldDouble = 888.88, - testFieldDoubleArray = new[] { 888.81, 888.82, 888.83 }, - testFieldDoubleArrayNullable = new double?[] { 888.11, 888.12, null, 888.13 }, - testFieldDoubleNullable = 222.22, - testFieldEnum1 = TableAllTypeEnumType1.e3, - testFieldEnum1Array = new[] { TableAllTypeEnumType1.e5, TableAllTypeEnumType1.e2, TableAllTypeEnumType1.e1 }, - testFieldEnum1ArrayNullable = new TableAllTypeEnumType1?[] { TableAllTypeEnumType1.e5, TableAllTypeEnumType1.e2, null, TableAllTypeEnumType1.e1 }, - testFieldEnum1Nullable = TableAllTypeEnumType1.e2, - testFieldEnum2 = TableAllTypeEnumType2.f2, - testFieldEnum2Array = new[] { TableAllTypeEnumType2.f3, TableAllTypeEnumType2.f1 }, - testFieldEnum2ArrayNullable = new TableAllTypeEnumType2?[] { TableAllTypeEnumType2.f3, null, TableAllTypeEnumType2.f1 }, - testFieldEnum2Nullable = TableAllTypeEnumType2.f3, - testFieldFloat = 777.77F, - testFieldFloatArray = new[] { 777.71F, 777.72F, 777.73F }, - testFieldFloatArrayNullable = new float?[] { 777.71F, 777.72F, null, 777.73F }, - testFieldFloatNullable = 333.33F, - testFieldGuid = Guid.NewGuid(), - testFieldGuidArray = new[] { Guid.NewGuid(), Guid.NewGuid() }, - testFieldGuidArrayNullable = new Guid?[] { Guid.NewGuid(), null, Guid.NewGuid() }, - testFieldGuidNullable = Guid.NewGuid(), - testFieldHStore = new Dictionary { { "111", "value111" }, { "222", "value222" }, { "333", "value333" } }, - testFieldHStoreArray = new[] { new Dictionary { { "111", "value111" }, { "222", "value222" }, { "333", "value333" } }, new Dictionary { { "444", "value444" }, { "555", "value555" }, { "666", "value666" } } }, - testFieldInet = IPAddress.Parse("192.168.1.1"), - testFieldInetArray = new[] { IPAddress.Parse("192.168.1.1"), IPAddress.Parse("192.168.1.2"), IPAddress.Parse("192.168.1.3") }, - testFieldInt = int.MaxValue, - testFieldInt4range = new NpgsqlRange(10, 20), - testFieldInt4rangeArray = new[] { new NpgsqlRange(10, 20), new NpgsqlRange(50, 100), new NpgsqlRange(200, 300) }, - testFieldInt4rangeArrayNullable = new NpgsqlRange?[] { new NpgsqlRange(10, 20), new NpgsqlRange(50, 100), null, new NpgsqlRange(200, 300) }, - testFieldInt4rangeNullable = new NpgsqlRange(100, 200), - testFieldInt8range = new NpgsqlRange(100, 200), - testFieldInt8rangeArray = new[] { new NpgsqlRange(100, 200), new NpgsqlRange(500, 1000), new NpgsqlRange(2000, 3000) }, - testFieldInt8rangeArrayNullable = new NpgsqlRange?[] { new NpgsqlRange(100, 200), new NpgsqlRange(500, 1000), null, new NpgsqlRange(2000, 3000) }, - testFieldInt8rangeNullable = new NpgsqlRange(1000, 2000), - testFieldIntArray = new[] { 1, 2, 3, 4, 5 }, - testFieldIntArrayNullable = new int?[] { 1, 2, 3, null, 4, 5 }, - testFieldIntNullable = int.MinValue, - testFieldJArray = JArray.Parse("[1,2,3,4,5]"), - testFieldJArrayArray = new[] { JArray.Parse("[1,2,3,4,5]"), JArray.Parse("[10,20,30,40,50]") }, - testFieldJObject = JObject.Parse("{ \"a\":1, \"b\":2, \"c\":3 }"), - testFieldJObjectArray = new[] { JObject.Parse("{ \"a\":1, \"b\":2, \"c\":3 }"), JObject.Parse("{ \"a\":10, \"b\":20, \"c\":30 }") }, - testFieldJToken = JToken.Parse("{ \"a\":1, \"b\":2, \"c\":3, \"d\":[1,2,3,4,5] }"), - testFieldJTokenArray = new[] { JToken.Parse("{ \"a\":1, \"b\":2, \"c\":3, \"d\":[1,2,3,4,5] }"), JToken.Parse("{ \"a\":10, \"b\":20, \"c\":30, \"d\":[10,20,30,40,50] }") }, - testFieldLong = long.MaxValue, - testFieldLongArray = new long[] { 10, 20, 30, 40, 50 }, - testFieldMacaddr = PhysicalAddress.Parse("A1-A2-CD-DD-FF-02"), - testFieldMacaddrArray = new[] { PhysicalAddress.Parse("A1-A2-CD-DD-FF-02"), PhysicalAddress.Parse("A2-22-22-22-22-02") }, - testFieldNpgsqlBox = new NpgsqlBox(10, 100, 100, 10), - testFieldNpgsqlBoxArray = new[] { new NpgsqlBox(10, 100, 100, 10), new NpgsqlBox(200, 2000, 2000, 200) }, - testFieldNpgsqlBoxArrayNullable = new NpgsqlBox?[] { new NpgsqlBox(10, 100, 100, 10), null, new NpgsqlBox(200, 2000, 2000, 200) }, - testFieldNpgsqlBoxNullable = new NpgsqlBox(200, 2000, 2000, 200), - testFieldNpgsqlCircle = new NpgsqlCircle(50, 50, 100), - testFieldNpgsqlCircleArray = new[] { new NpgsqlCircle(50, 50, 100), new NpgsqlCircle(80, 80, 100) }, - testFieldNpgsqlCircleArrayNullable = new NpgsqlCircle?[] { new NpgsqlCircle(50, 50, 100), null, new NpgsqlCircle(80, 80, 100) }, - testFieldNpgsqlCircleNullable = new NpgsqlCircle(80, 80, 100), - testFieldNpgsqlLine = new NpgsqlLine(30, 30, 30), - testFieldNpgsqlLineArray = new[] { new NpgsqlLine(30, 30, 30), new NpgsqlLine(35, 35, 35) }, - testFieldNpgsqlLineArrayNullable = new NpgsqlLine?[] { new NpgsqlLine(30, 30, 30), null, new NpgsqlLine(35, 35, 35) }, - testFieldNpgsqlLineNullable = new NpgsqlLine(60, 60, 60), - testFieldNpgsqlLSeg = new NpgsqlLSeg(80, 10, 800, 20), - testFieldNpgsqlLSegArray = new[] { new NpgsqlLSeg(80, 10, 800, 20), new NpgsqlLSeg(180, 20, 260, 50) }, - testFieldNpgsqlLSegArrayNullable = new NpgsqlLSeg?[] { new NpgsqlLSeg(80, 10, 800, 20), null, new NpgsqlLSeg(180, 20, 260, 50) }, - testFieldNpgsqlLSegNullable = new NpgsqlLSeg(180, 20, 260, 50), - testFieldNpgsqlPath = new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)), - testFieldNpgsqlPathArray = new[] { new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)), new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)) }, - testFieldNpgsqlPathArrayNullable = new NpgsqlPath?[] { new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)), null, new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)) }, - testFieldNpgsqlPathNullable = new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)), - testFieldNpgsqlPoint = new NpgsqlPoint(666, 666), - testFieldNpgsqlPointArray = new[] { new NpgsqlPoint(666, 666), new NpgsqlPoint(888, 888) }, - testFieldNpgsqlPointArrayNullable = new NpgsqlPoint?[] { new NpgsqlPoint(666, 666), null, new NpgsqlPoint(888, 888) }, - testFieldNpgsqlPointNullable = new NpgsqlPoint(888, 888), - testFieldNpgsqlPolygon = new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)), - testFieldNpgsqlPolygonArray = new[] { new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)), new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)) }, - testFieldNpgsqlPolygonArrayNullable = new NpgsqlPolygon?[] { new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)), null, new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)) }, - testFieldNpgsqlPolygonNullable = new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)), - testFieldNumrange = new NpgsqlRange(888.88M, 999.99M), - testFieldNumrangeArray = new[] { new NpgsqlRange(888.88M, 999.99M), new NpgsqlRange(18888.88M, 19998.99M) }, - testFieldNumrangeArrayNullable = new NpgsqlRange?[] { new NpgsqlRange(888.88M, 999.99M), null, new NpgsqlRange(18888.88M, 19998.99M) }, - testFieldNumrangeNullable = new NpgsqlRange(18888.88M, 19998.99M), - testFieldPostgisGeometry = new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), - testFieldPostgisGeometryArray = new PostgisGeometry[] { - new PostgisPoint(555,551), - new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), - new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), - new PostgisMultiPolygon(new []{ - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) - }) - }, - testFieldPostgisGeometryCollection = new PostgisGeometryCollection(new PostgisGeometry[] { - new PostgisPoint(555,551), - new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), - new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), - new PostgisMultiPolygon(new []{ - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) - }) - }), - testFieldPostgisGeometryCollectionArray = new[] { - new PostgisGeometryCollection(new PostgisGeometry[] { - new PostgisPoint(555,551), - new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), - new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), - new PostgisMultiPolygon(new []{ - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) - }) - }),new PostgisGeometryCollection(new PostgisGeometry[] { - new PostgisPoint(555,551), - new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), - new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), - new PostgisMultiPolygon(new []{ - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) - }) - }) - }, - testFieldPostgisLineString = new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), - testFieldPostgisLineStringArray = new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 220) }) }, - testFieldPostgisMultiPoint = new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), - testFieldPostgisMultiPointArray = new[] { new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), new PostgisMultiPoint(new[] { new Coordinate2D(120, 121), new Coordinate2D(1210, 1220) }) }, - testFieldPostgisPoint = new PostgisPoint(555, 551), - testFieldPostgisPointArray = new[] { new PostgisPoint(555, 551), new PostgisPoint(53355, 3551) }, - testFieldPostgisPolygon = new PostgisPolygon(new[] { new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - testFieldPostgisPolygonArray = new[]{ - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) - }, - testFieldPostgisPostgisMultiLineString = new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), - testFieldPostgisPostgisMultiLineStringArray = new[] { - new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), - new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 220) }) , new PostgisLineString(new[] { new Coordinate2D(820, 821), new Coordinate2D(800, 810) }) }) - }, - testFieldPostgisPostgisMultiPolygon = new PostgisMultiPolygon(new[]{ - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) - }), - testFieldPostgisPostgisMultiPolygonArray = new[] { - new PostgisMultiPolygon(new[]{ - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) - }), - new PostgisMultiPolygon(new[]{ - new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), - new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) - }) - }, - testFieldSByte = sbyte.MaxValue, - testFieldSByteArray = new sbyte[] { 1, 2, 3, 4, 5 }, - testFieldSByteArrayNullable = new sbyte?[] { 1, 2, 3, null, 4, 5 }, - testFieldSByteNullable = sbyte.MinValue, - testFieldShort = short.MaxValue, - testFieldShortArray = new short[] { 1, 2, 3, 4, 5 }, - testFieldShortArrayNullable = new short?[] { 1, 2, 3, null, 4, 5 }, - testFieldShortNullable = short.MinValue, - testFieldString = "йString", - testFieldStringArray = new[] { "йString1", "йString2", null, "йString3" }, - testFieldTimeSpan = TimeSpan.FromDays(1), - testFieldTimeSpanArray = new[] { TimeSpan.FromDays(1), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(60) }, - testFieldTimeSpanArrayNullable = new TimeSpan?[] { TimeSpan.FromDays(1), TimeSpan.FromSeconds(10), null, TimeSpan.FromSeconds(60) }, - testFieldTimeSpanNullable = TimeSpan.FromSeconds(90), - testFieldTsrange = new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(1)), - testFieldTsrangeArray = new[] { new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(1)), new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(2)) }, - testFieldTsrangeArrayNullable = new NpgsqlRange?[] { new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(1)), null, new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(2)) }, - testFieldTsrangeNullable = new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(2)), - testFieldUInt = uint.MaxValue, - testFieldUIntArray = new uint[] { 1, 2, 3, 4, 5 }, - testFieldUIntArrayNullable = new uint?[] { 1, 2, 3, null, 4, 5 }, - testFieldUIntNullable = uint.MinValue, - testFieldULong = ulong.MaxValue, - testFieldULongArray = new ulong[] { 10, 20, 30, 40, 50 }, - testFieldULongArrayNullable = new ulong?[] { 10, 20, 30, null, 40, 50 }, - testFieldULongNullable = ulong.MinValue, - testFieldUShort = ushort.MaxValue, - testFieldUShortArray = new ushort[] { 11, 12, 13, 14, 15 }, - testFieldUShortArrayNullable = new ushort?[] { 11, 12, 13, null, 14, 15 }, - testFieldUShortNullable = ushort.MinValue, - testFielLongArrayNullable = new long?[] { 500, 600, 700, null, 999, 1000 }, - testFielLongNullable = long.MinValue - }; - var item3 = insert.AppendData(item2).ExecuteInserted().First(); - var newitem2 = select.Where(a => a.Id == item3.Id).ToOne(); + var item2 = new TableAllType + { + testFieldBitArray = new BitArray(Encoding.UTF8.GetBytes("")), + testFieldBitArrayArray = new[] { new BitArray(Encoding.UTF8.GetBytes("й")), new BitArray(Encoding.UTF8.GetBytes("")) }, + testFieldBool = true, + testFieldBoolArray = new[] { true, true, false, false }, + testFieldBoolArrayNullable = new bool?[] { true, true, null, false, false }, + testFieldBoolNullable = true, + testFieldByte = byte.MaxValue, + testFieldByteArray = new byte[] { 0, 1, 2, 3, 4, 5, 6 }, + testFieldByteArrayNullable = new byte?[] { 0, 1, 2, 3, null, 4, 5, 6 }, + testFieldByteNullable = byte.MinValue, + testFieldBytes = Encoding.UTF8.GetBytes("й"), + testFieldBytesArray = new[] { Encoding.UTF8.GetBytes("й"), Encoding.UTF8.GetBytes("й") }, + testFieldCidr = (IPAddress.Parse("10.0.0.0"), 8), + testFieldCidrArray = new[] { (IPAddress.Parse("10.0.0.0"), 8), (IPAddress.Parse("192.168.0.0"), 16) }, + testFieldCidrArrayNullable = new (IPAddress, int)?[] { (IPAddress.Parse("10.0.0.0"), 8), null, (IPAddress.Parse("192.168.0.0"), 16) }, + testFieldCidrNullable = (IPAddress.Parse("192.168.0.0"), 16), + testFieldDateTime = DateTime.Now, + testFieldDateTimeArray = new[] { DateTime.Now, DateTime.Now.AddHours(2) }, + testFieldDateTimeArrayNullable = new DateTime?[] { DateTime.Now, null, DateTime.Now.AddHours(2) }, + testFieldDateTimeNullable = DateTime.Now.AddDays(-1), + testFieldDecimal = 999.99M, + testFieldDecimalArray = new[] { 999.91M, 999.92M, 999.93M }, + testFieldDecimalArrayNullable = new decimal?[] { 998.11M, 998.12M, 998.13M }, + testFieldDecimalNullable = 111.11M, + testFieldDouble = 888.88, + testFieldDoubleArray = new[] { 888.81, 888.82, 888.83 }, + testFieldDoubleArrayNullable = new double?[] { 888.11, 888.12, null, 888.13 }, + testFieldDoubleNullable = 222.22, + testFieldEnum1 = TableAllTypeEnumType1.e3, + testFieldEnum1Array = new[] { TableAllTypeEnumType1.e5, TableAllTypeEnumType1.e2, TableAllTypeEnumType1.e1 }, + testFieldEnum1ArrayNullable = new TableAllTypeEnumType1?[] { TableAllTypeEnumType1.e5, TableAllTypeEnumType1.e2, null, TableAllTypeEnumType1.e1 }, + testFieldEnum1Nullable = TableAllTypeEnumType1.e2, + testFieldEnum2 = TableAllTypeEnumType2.f2, + testFieldEnum2Array = new[] { TableAllTypeEnumType2.f3, TableAllTypeEnumType2.f1 }, + testFieldEnum2ArrayNullable = new TableAllTypeEnumType2?[] { TableAllTypeEnumType2.f3, null, TableAllTypeEnumType2.f1 }, + testFieldEnum2Nullable = TableAllTypeEnumType2.f3, + testFieldFloat = 777.77F, + testFieldFloatArray = new[] { 777.71F, 777.72F, 777.73F }, + testFieldFloatArrayNullable = new float?[] { 777.71F, 777.72F, null, 777.73F }, + testFieldFloatNullable = 333.33F, + testFieldGuid = Guid.NewGuid(), + testFieldGuidArray = new[] { Guid.NewGuid(), Guid.NewGuid() }, + testFieldGuidArrayNullable = new Guid?[] { Guid.NewGuid(), null, Guid.NewGuid() }, + testFieldGuidNullable = Guid.NewGuid(), + testFieldHStore = new Dictionary { { "111", "value111" }, { "222", "value222" }, { "333", "value333" } }, + testFieldHStoreArray = new[] { new Dictionary { { "111", "value111" }, { "222", "value222" }, { "333", "value333" } }, new Dictionary { { "444", "value444" }, { "555", "value555" }, { "666", "value666" } } }, + testFieldInet = IPAddress.Parse("192.168.1.1"), + testFieldInetArray = new[] { IPAddress.Parse("192.168.1.1"), IPAddress.Parse("192.168.1.2"), IPAddress.Parse("192.168.1.3") }, + testFieldInt = int.MaxValue, + testFieldInt4range = new NpgsqlRange(10, 20), + testFieldInt4rangeArray = new[] { new NpgsqlRange(10, 20), new NpgsqlRange(50, 100), new NpgsqlRange(200, 300) }, + testFieldInt4rangeArrayNullable = new NpgsqlRange?[] { new NpgsqlRange(10, 20), new NpgsqlRange(50, 100), null, new NpgsqlRange(200, 300) }, + testFieldInt4rangeNullable = new NpgsqlRange(100, 200), + testFieldInt8range = new NpgsqlRange(100, 200), + testFieldInt8rangeArray = new[] { new NpgsqlRange(100, 200), new NpgsqlRange(500, 1000), new NpgsqlRange(2000, 3000) }, + testFieldInt8rangeArrayNullable = new NpgsqlRange?[] { new NpgsqlRange(100, 200), new NpgsqlRange(500, 1000), null, new NpgsqlRange(2000, 3000) }, + testFieldInt8rangeNullable = new NpgsqlRange(1000, 2000), + testFieldIntArray = new[] { 1, 2, 3, 4, 5 }, + testFieldIntArrayNullable = new int?[] { 1, 2, 3, null, 4, 5 }, + testFieldIntNullable = int.MinValue, + testFieldJArray = JArray.Parse("[1,2,3,4,5]"), + testFieldJArrayArray = new[] { JArray.Parse("[1,2,3,4,5]"), JArray.Parse("[10,20,30,40,50]") }, + testFieldJObject = JObject.Parse("{ \"a\":1, \"b\":2, \"c\":3 }"), + testFieldJObjectArray = new[] { JObject.Parse("{ \"a\":1, \"b\":2, \"c\":3 }"), JObject.Parse("{ \"a\":10, \"b\":20, \"c\":30 }") }, + testFieldJToken = JToken.Parse("{ \"a\":1, \"b\":2, \"c\":3, \"d\":[1,2,3,4,5] }"), + testFieldJTokenArray = new[] { JToken.Parse("{ \"a\":1, \"b\":2, \"c\":3, \"d\":[1,2,3,4,5] }"), JToken.Parse("{ \"a\":10, \"b\":20, \"c\":30, \"d\":[10,20,30,40,50] }") }, + testFieldLong = long.MaxValue, + testFieldLongArray = new long[] { 10, 20, 30, 40, 50 }, + testFieldMacaddr = PhysicalAddress.Parse("A1-A2-CD-DD-FF-02"), + testFieldMacaddrArray = new[] { PhysicalAddress.Parse("A1-A2-CD-DD-FF-02"), PhysicalAddress.Parse("A2-22-22-22-22-02") }, + testFieldNpgsqlBox = new NpgsqlBox(10, 100, 100, 10), + testFieldNpgsqlBoxArray = new[] { new NpgsqlBox(10, 100, 100, 10), new NpgsqlBox(200, 2000, 2000, 200) }, + testFieldNpgsqlBoxArrayNullable = new NpgsqlBox?[] { new NpgsqlBox(10, 100, 100, 10), null, new NpgsqlBox(200, 2000, 2000, 200) }, + testFieldNpgsqlBoxNullable = new NpgsqlBox(200, 2000, 2000, 200), + testFieldNpgsqlCircle = new NpgsqlCircle(50, 50, 100), + testFieldNpgsqlCircleArray = new[] { new NpgsqlCircle(50, 50, 100), new NpgsqlCircle(80, 80, 100) }, + testFieldNpgsqlCircleArrayNullable = new NpgsqlCircle?[] { new NpgsqlCircle(50, 50, 100), null, new NpgsqlCircle(80, 80, 100) }, + testFieldNpgsqlCircleNullable = new NpgsqlCircle(80, 80, 100), + testFieldNpgsqlLine = new NpgsqlLine(30, 30, 30), + testFieldNpgsqlLineArray = new[] { new NpgsqlLine(30, 30, 30), new NpgsqlLine(35, 35, 35) }, + testFieldNpgsqlLineArrayNullable = new NpgsqlLine?[] { new NpgsqlLine(30, 30, 30), null, new NpgsqlLine(35, 35, 35) }, + testFieldNpgsqlLineNullable = new NpgsqlLine(60, 60, 60), + testFieldNpgsqlLSeg = new NpgsqlLSeg(80, 10, 800, 20), + testFieldNpgsqlLSegArray = new[] { new NpgsqlLSeg(80, 10, 800, 20), new NpgsqlLSeg(180, 20, 260, 50) }, + testFieldNpgsqlLSegArrayNullable = new NpgsqlLSeg?[] { new NpgsqlLSeg(80, 10, 800, 20), null, new NpgsqlLSeg(180, 20, 260, 50) }, + testFieldNpgsqlLSegNullable = new NpgsqlLSeg(180, 20, 260, 50), + testFieldNpgsqlPath = new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)), + testFieldNpgsqlPathArray = new[] { new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)), new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)) }, + testFieldNpgsqlPathArrayNullable = new NpgsqlPath?[] { new NpgsqlPath(new NpgsqlPoint(10, 10), new NpgsqlPoint(15, 10), new NpgsqlPoint(17, 10), new NpgsqlPoint(19, 10)), null, new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)) }, + testFieldNpgsqlPathNullable = new NpgsqlPath(new NpgsqlPoint(210, 10), new NpgsqlPoint(215, 10), new NpgsqlPoint(217, 10), new NpgsqlPoint(219, 10)), + testFieldNpgsqlPoint = new NpgsqlPoint(666, 666), + testFieldNpgsqlPointArray = new[] { new NpgsqlPoint(666, 666), new NpgsqlPoint(888, 888) }, + testFieldNpgsqlPointArrayNullable = new NpgsqlPoint?[] { new NpgsqlPoint(666, 666), null, new NpgsqlPoint(888, 888) }, + testFieldNpgsqlPointNullable = new NpgsqlPoint(888, 888), + testFieldNpgsqlPolygon = new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)), + testFieldNpgsqlPolygonArray = new[] { new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)), new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)) }, + testFieldNpgsqlPolygonArrayNullable = new NpgsqlPolygon?[] { new NpgsqlPolygon(new NpgsqlPoint(36, 30), new NpgsqlPoint(36, 50), new NpgsqlPoint(38, 80), new NpgsqlPoint(36, 30)), null, new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)) }, + testFieldNpgsqlPolygonNullable = new NpgsqlPolygon(new NpgsqlPoint(136, 130), new NpgsqlPoint(136, 150), new NpgsqlPoint(138, 180), new NpgsqlPoint(136, 130)), + testFieldNumrange = new NpgsqlRange(888.88M, 999.99M), + testFieldNumrangeArray = new[] { new NpgsqlRange(888.88M, 999.99M), new NpgsqlRange(18888.88M, 19998.99M) }, + testFieldNumrangeArrayNullable = new NpgsqlRange?[] { new NpgsqlRange(888.88M, 999.99M), null, new NpgsqlRange(18888.88M, 19998.99M) }, + testFieldNumrangeNullable = new NpgsqlRange(18888.88M, 19998.99M), + testFieldPostgisGeometry = new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), + testFieldPostgisGeometryArray = new PostgisGeometry[] { + new PostgisPoint(555,551), + new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), + new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), + new PostgisMultiPolygon(new []{ + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) + }) + }, + testFieldPostgisGeometryCollection = new PostgisGeometryCollection(new PostgisGeometry[] { + new PostgisPoint(555,551), + new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), + new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), + new PostgisMultiPolygon(new []{ + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) + }) + }), + testFieldPostgisGeometryCollectionArray = new[] { + new PostgisGeometryCollection(new PostgisGeometry[] { + new PostgisPoint(555,551), + new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), + new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), + new PostgisMultiPolygon(new []{ + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) + }) + }),new PostgisGeometryCollection(new PostgisGeometry[] { + new PostgisPoint(555,551), + new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), + new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), + new PostgisMultiPolygon(new []{ + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) + }) + }) + }, + testFieldPostgisLineString = new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), + testFieldPostgisLineStringArray = new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 220) }) }, + testFieldPostgisMultiPoint = new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), + testFieldPostgisMultiPointArray = new[] { new PostgisMultiPoint(new[] { new Coordinate2D(20, 21), new Coordinate2D(210, 220) }), new PostgisMultiPoint(new[] { new Coordinate2D(120, 121), new Coordinate2D(1210, 1220) }) }, + testFieldPostgisPoint = new PostgisPoint(555, 551), + testFieldPostgisPointArray = new[] { new PostgisPoint(555, 551), new PostgisPoint(53355, 3551) }, + testFieldPostgisPolygon = new PostgisPolygon(new[] { new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + testFieldPostgisPolygonArray = new[]{ + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) + }, + testFieldPostgisPostgisMultiLineString = new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }), new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), + testFieldPostgisPostgisMultiLineStringArray = new[] { + new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110) }) , new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 210) }) }), + new PostgisMultiLineString(new[] { new PostgisLineString(new[] { new Coordinate2D(20, 21), new Coordinate2D(200, 220) }) , new PostgisLineString(new[] { new Coordinate2D(820, 821), new Coordinate2D(800, 810) }) }) + }, + testFieldPostgisPostgisMultiPolygon = new PostgisMultiPolygon(new[]{ + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) + }), + testFieldPostgisPostgisMultiPolygonArray = new[] { + new PostgisMultiPolygon(new[]{ + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) + }), + new PostgisMultiPolygon(new[]{ + new PostgisPolygon(new []{ new[] { new Coordinate2D(10, 11), new Coordinate2D(100, 110), new Coordinate2D(300, 310), new Coordinate2D(10, 11) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }), + new PostgisPolygon(new []{ new[] { new Coordinate2D(50, 51), new Coordinate2D(500, 510), new Coordinate2D(800, 810), new Coordinate2D(50, 51) }, new[] { new Coordinate2D(20, 11), new Coordinate2D(200, 110), new Coordinate2D(100, 310), new Coordinate2D(20, 11) } }) + }) + }, + testFieldSByte = sbyte.MaxValue, + testFieldSByteArray = new sbyte[] { 1, 2, 3, 4, 5 }, + testFieldSByteArrayNullable = new sbyte?[] { 1, 2, 3, null, 4, 5 }, + testFieldSByteNullable = sbyte.MinValue, + testFieldShort = short.MaxValue, + testFieldShortArray = new short[] { 1, 2, 3, 4, 5 }, + testFieldShortArrayNullable = new short?[] { 1, 2, 3, null, 4, 5 }, + testFieldShortNullable = short.MinValue, + testFieldString = "йString", + testFieldStringArray = new[] { "йString1", "йString2", null, "йString3" }, + testFieldTimeSpan = TimeSpan.FromDays(1), + testFieldTimeSpanArray = new[] { TimeSpan.FromDays(1), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(60) }, + testFieldTimeSpanArrayNullable = new TimeSpan?[] { TimeSpan.FromDays(1), TimeSpan.FromSeconds(10), null, TimeSpan.FromSeconds(60) }, + testFieldTimeSpanNullable = TimeSpan.FromSeconds(90), + testFieldTsrange = new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(1)), + testFieldTsrangeArray = new[] { new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(1)), new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(2)) }, + testFieldTsrangeArrayNullable = new NpgsqlRange?[] { new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(1)), null, new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(2)) }, + testFieldTsrangeNullable = new NpgsqlRange(DateTime.Now, DateTime.Now.AddMonths(2)), + testFieldUInt = uint.MaxValue, + testFieldUIntArray = new uint[] { 1, 2, 3, 4, 5 }, + testFieldUIntArrayNullable = new uint?[] { 1, 2, 3, null, 4, 5 }, + testFieldUIntNullable = uint.MinValue, + testFieldULong = ulong.MaxValue, + testFieldULongArray = new ulong[] { 10, 20, 30, 40, 50 }, + testFieldULongArrayNullable = new ulong?[] { 10, 20, 30, null, 40, 50 }, + testFieldULongNullable = ulong.MinValue, + testFieldUShort = ushort.MaxValue, + testFieldUShortArray = new ushort[] { 11, 12, 13, 14, 15 }, + testFieldUShortArrayNullable = new ushort?[] { 11, 12, 13, null, 14, 15 }, + testFieldUShortNullable = ushort.MinValue, + testFielLongArrayNullable = new long?[] { 500, 600, 700, null, 999, 1000 }, + testFielLongNullable = long.MinValue + }; + var item3 = insert.AppendData(item2).ExecuteInserted().First(); + var newitem2 = select.Where(a => a.Id == item3.Id).ToOne(); - var items = select.ToList(); - } + var items = select.ToList(); + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - public bool testFieldBool { get; set; } - public sbyte testFieldSByte { get; set; } - public short testFieldShort { get; set; } - public int testFieldInt { get; set; } - public long testFieldLong { get; set; } - public byte testFieldByte { get; set; } - public ushort testFieldUShort { get; set; } - public uint testFieldUInt { get; set; } - public ulong testFieldULong { get; set; } - public double testFieldDouble { get; set; } - public float testFieldFloat { get; set; } - public decimal testFieldDecimal { get; set; } - public TimeSpan testFieldTimeSpan { get; set; } - public DateTime testFieldDateTime { get; set; } - public byte[] testFieldBytes { get; set; } - public string testFieldString { get; set; } - public Guid testFieldGuid { get; set; } - public NpgsqlPoint testFieldNpgsqlPoint { get; set; } - public NpgsqlLine testFieldNpgsqlLine { get; set; } - public NpgsqlLSeg testFieldNpgsqlLSeg { get; set; } - public NpgsqlBox testFieldNpgsqlBox { get; set; } - public NpgsqlPath testFieldNpgsqlPath { get; set; } - public NpgsqlPolygon testFieldNpgsqlPolygon { get; set; } - public NpgsqlCircle testFieldNpgsqlCircle { get; set; } - public (IPAddress Address, int Subnet) testFieldCidr { get; set; } - public NpgsqlRange testFieldInt4range { get; set; } - public NpgsqlRange testFieldInt8range { get; set; } - public NpgsqlRange testFieldNumrange { get; set; } - public NpgsqlRange testFieldTsrange { get; set; } + public bool testFieldBool { get; set; } + public sbyte testFieldSByte { get; set; } + public short testFieldShort { get; set; } + public int testFieldInt { get; set; } + public long testFieldLong { get; set; } + public byte testFieldByte { get; set; } + public ushort testFieldUShort { get; set; } + public uint testFieldUInt { get; set; } + public ulong testFieldULong { get; set; } + public double testFieldDouble { get; set; } + public float testFieldFloat { get; set; } + public decimal testFieldDecimal { get; set; } + public TimeSpan testFieldTimeSpan { get; set; } + public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } + public string testFieldString { get; set; } + public Guid testFieldGuid { get; set; } + public NpgsqlPoint testFieldNpgsqlPoint { get; set; } + public NpgsqlLine testFieldNpgsqlLine { get; set; } + public NpgsqlLSeg testFieldNpgsqlLSeg { get; set; } + public NpgsqlBox testFieldNpgsqlBox { get; set; } + public NpgsqlPath testFieldNpgsqlPath { get; set; } + public NpgsqlPolygon testFieldNpgsqlPolygon { get; set; } + public NpgsqlCircle testFieldNpgsqlCircle { get; set; } + public (IPAddress Address, int Subnet) testFieldCidr { get; set; } + public NpgsqlRange testFieldInt4range { get; set; } + public NpgsqlRange testFieldInt8range { get; set; } + public NpgsqlRange testFieldNumrange { get; set; } + public NpgsqlRange testFieldTsrange { get; set; } - public bool? testFieldBoolNullable { get; set; } - public sbyte? testFieldSByteNullable { get; set; } - public short? testFieldShortNullable { get; set; } - public int? testFieldIntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? testFieldByteNullable { get; set; } - public ushort? testFieldUShortNullable { get; set; } - public uint? testFieldUIntNullable { get; set; } - public ulong? testFieldULongNullable { get; set; } - public double? testFieldDoubleNullable { get; set; } - public float? testFieldFloatNullable { get; set; } - public decimal? testFieldDecimalNullable { get; set; } - public TimeSpan? testFieldTimeSpanNullable { get; set; } - public DateTime? testFieldDateTimeNullable { get; set; } - public Guid? testFieldGuidNullable { get; set; } - public NpgsqlPoint? testFieldNpgsqlPointNullable { get; set; } - public NpgsqlLine? testFieldNpgsqlLineNullable { get; set; } - public NpgsqlLSeg? testFieldNpgsqlLSegNullable { get; set; } - public NpgsqlBox? testFieldNpgsqlBoxNullable { get; set; } - public NpgsqlPath? testFieldNpgsqlPathNullable { get; set; } - public NpgsqlPolygon? testFieldNpgsqlPolygonNullable { get; set; } - public NpgsqlCircle? testFieldNpgsqlCircleNullable { get; set; } - public (IPAddress Address, int Subnet)? testFieldCidrNullable { get; set; } - public NpgsqlRange? testFieldInt4rangeNullable { get; set; } - public NpgsqlRange? testFieldInt8rangeNullable { get; set; } - public NpgsqlRange? testFieldNumrangeNullable { get; set; } - public NpgsqlRange? testFieldTsrangeNullable { get; set; } + public bool? testFieldBoolNullable { get; set; } + public sbyte? testFieldSByteNullable { get; set; } + public short? testFieldShortNullable { get; set; } + public int? testFieldIntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? testFieldByteNullable { get; set; } + public ushort? testFieldUShortNullable { get; set; } + public uint? testFieldUIntNullable { get; set; } + public ulong? testFieldULongNullable { get; set; } + public double? testFieldDoubleNullable { get; set; } + public float? testFieldFloatNullable { get; set; } + public decimal? testFieldDecimalNullable { get; set; } + public TimeSpan? testFieldTimeSpanNullable { get; set; } + public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } + public NpgsqlPoint? testFieldNpgsqlPointNullable { get; set; } + public NpgsqlLine? testFieldNpgsqlLineNullable { get; set; } + public NpgsqlLSeg? testFieldNpgsqlLSegNullable { get; set; } + public NpgsqlBox? testFieldNpgsqlBoxNullable { get; set; } + public NpgsqlPath? testFieldNpgsqlPathNullable { get; set; } + public NpgsqlPolygon? testFieldNpgsqlPolygonNullable { get; set; } + public NpgsqlCircle? testFieldNpgsqlCircleNullable { get; set; } + public (IPAddress Address, int Subnet)? testFieldCidrNullable { get; set; } + public NpgsqlRange? testFieldInt4rangeNullable { get; set; } + public NpgsqlRange? testFieldInt8rangeNullable { get; set; } + public NpgsqlRange? testFieldNumrangeNullable { get; set; } + public NpgsqlRange? testFieldTsrangeNullable { get; set; } - public BitArray testFieldBitArray { get; set; } - public IPAddress testFieldInet { get; set; } - public PhysicalAddress testFieldMacaddr { get; set; } - public JToken testFieldJToken { get; set; } - public JObject testFieldJObject { get; set; } - public JArray testFieldJArray { get; set; } - public Dictionary testFieldHStore { get; set; } - public PostgisPoint testFieldPostgisPoint { get; set; } - public PostgisLineString testFieldPostgisLineString { get; set; } - public PostgisPolygon testFieldPostgisPolygon { get; set; } - public PostgisMultiPoint testFieldPostgisMultiPoint { get; set; } - public PostgisMultiLineString testFieldPostgisPostgisMultiLineString { get; set; } - public PostgisMultiPolygon testFieldPostgisPostgisMultiPolygon { get; set; } - public PostgisGeometry testFieldPostgisGeometry { get; set; } - public PostgisGeometryCollection testFieldPostgisGeometryCollection { get; set; } + public BitArray testFieldBitArray { get; set; } + public IPAddress testFieldInet { get; set; } + public PhysicalAddress testFieldMacaddr { get; set; } + public JToken testFieldJToken { get; set; } + public JObject testFieldJObject { get; set; } + public JArray testFieldJArray { get; set; } + public Dictionary testFieldHStore { get; set; } + public PostgisPoint testFieldPostgisPoint { get; set; } + public PostgisLineString testFieldPostgisLineString { get; set; } + public PostgisPolygon testFieldPostgisPolygon { get; set; } + public PostgisMultiPoint testFieldPostgisMultiPoint { get; set; } + public PostgisMultiLineString testFieldPostgisPostgisMultiLineString { get; set; } + public PostgisMultiPolygon testFieldPostgisPostgisMultiPolygon { get; set; } + public PostgisGeometry testFieldPostgisGeometry { get; set; } + public PostgisGeometryCollection testFieldPostgisGeometryCollection { get; set; } - public TableAllTypeEnumType1 testFieldEnum1 { get; set; } - public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } - public TableAllTypeEnumType2 testFieldEnum2 { get; set; } - public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } + public TableAllTypeEnumType1 testFieldEnum1 { get; set; } + public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } + public TableAllTypeEnumType2 testFieldEnum2 { get; set; } + public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } - /* array */ - public bool[] testFieldBoolArray { get; set; } - public sbyte[] testFieldSByteArray { get; set; } - public short[] testFieldShortArray { get; set; } - public int[] testFieldIntArray { get; set; } - public long[] testFieldLongArray { get; set; } - public byte[] testFieldByteArray { get; set; } - public ushort[] testFieldUShortArray { get; set; } - public uint[] testFieldUIntArray { get; set; } - public ulong[] testFieldULongArray { get; set; } - public double[] testFieldDoubleArray { get; set; } - public float[] testFieldFloatArray { get; set; } - public decimal[] testFieldDecimalArray { get; set; } - public TimeSpan[] testFieldTimeSpanArray { get; set; } - public DateTime[] testFieldDateTimeArray { get; set; } - public byte[][] testFieldBytesArray { get; set; } - public string[] testFieldStringArray { get; set; } - public Guid[] testFieldGuidArray { get; set; } - public NpgsqlPoint[] testFieldNpgsqlPointArray { get; set; } - public NpgsqlLine[] testFieldNpgsqlLineArray { get; set; } - public NpgsqlLSeg[] testFieldNpgsqlLSegArray { get; set; } - public NpgsqlBox[] testFieldNpgsqlBoxArray { get; set; } - public NpgsqlPath[] testFieldNpgsqlPathArray { get; set; } - public NpgsqlPolygon[] testFieldNpgsqlPolygonArray { get; set; } - public NpgsqlCircle[] testFieldNpgsqlCircleArray { get; set; } - public (IPAddress Address, int Subnet)[] testFieldCidrArray { get; set; } - public NpgsqlRange[] testFieldInt4rangeArray { get; set; } - public NpgsqlRange[] testFieldInt8rangeArray { get; set; } - public NpgsqlRange[] testFieldNumrangeArray { get; set; } - public NpgsqlRange[] testFieldTsrangeArray { get; set; } + /* array */ + public bool[] testFieldBoolArray { get; set; } + public sbyte[] testFieldSByteArray { get; set; } + public short[] testFieldShortArray { get; set; } + public int[] testFieldIntArray { get; set; } + public long[] testFieldLongArray { get; set; } + public byte[] testFieldByteArray { get; set; } + public ushort[] testFieldUShortArray { get; set; } + public uint[] testFieldUIntArray { get; set; } + public ulong[] testFieldULongArray { get; set; } + public double[] testFieldDoubleArray { get; set; } + public float[] testFieldFloatArray { get; set; } + public decimal[] testFieldDecimalArray { get; set; } + public TimeSpan[] testFieldTimeSpanArray { get; set; } + public DateTime[] testFieldDateTimeArray { get; set; } + public byte[][] testFieldBytesArray { get; set; } + public string[] testFieldStringArray { get; set; } + public Guid[] testFieldGuidArray { get; set; } + public NpgsqlPoint[] testFieldNpgsqlPointArray { get; set; } + public NpgsqlLine[] testFieldNpgsqlLineArray { get; set; } + public NpgsqlLSeg[] testFieldNpgsqlLSegArray { get; set; } + public NpgsqlBox[] testFieldNpgsqlBoxArray { get; set; } + public NpgsqlPath[] testFieldNpgsqlPathArray { get; set; } + public NpgsqlPolygon[] testFieldNpgsqlPolygonArray { get; set; } + public NpgsqlCircle[] testFieldNpgsqlCircleArray { get; set; } + public (IPAddress Address, int Subnet)[] testFieldCidrArray { get; set; } + public NpgsqlRange[] testFieldInt4rangeArray { get; set; } + public NpgsqlRange[] testFieldInt8rangeArray { get; set; } + public NpgsqlRange[] testFieldNumrangeArray { get; set; } + public NpgsqlRange[] testFieldTsrangeArray { get; set; } - public bool?[] testFieldBoolArrayNullable { get; set; } - public sbyte?[] testFieldSByteArrayNullable { get; set; } - public short?[] testFieldShortArrayNullable { get; set; } - public int?[] testFieldIntArrayNullable { get; set; } - public long?[] testFielLongArrayNullable { get; set; } - public byte?[] testFieldByteArrayNullable { get; set; } - public ushort?[] testFieldUShortArrayNullable { get; set; } - public uint?[] testFieldUIntArrayNullable { get; set; } - public ulong?[] testFieldULongArrayNullable { get; set; } - public double?[] testFieldDoubleArrayNullable { get; set; } - public float?[] testFieldFloatArrayNullable { get; set; } - public decimal?[] testFieldDecimalArrayNullable { get; set; } - public TimeSpan?[] testFieldTimeSpanArrayNullable { get; set; } - public DateTime?[] testFieldDateTimeArrayNullable { get; set; } - public Guid?[] testFieldGuidArrayNullable { get; set; } - public NpgsqlPoint?[] testFieldNpgsqlPointArrayNullable { get; set; } - public NpgsqlLine?[] testFieldNpgsqlLineArrayNullable { get; set; } - public NpgsqlLSeg?[] testFieldNpgsqlLSegArrayNullable { get; set; } - public NpgsqlBox?[] testFieldNpgsqlBoxArrayNullable { get; set; } - public NpgsqlPath?[] testFieldNpgsqlPathArrayNullable { get; set; } - public NpgsqlPolygon?[] testFieldNpgsqlPolygonArrayNullable { get; set; } - public NpgsqlCircle?[] testFieldNpgsqlCircleArrayNullable { get; set; } - public (IPAddress Address, int Subnet)?[] testFieldCidrArrayNullable { get; set; } - public NpgsqlRange?[] testFieldInt4rangeArrayNullable { get; set; } - public NpgsqlRange?[] testFieldInt8rangeArrayNullable { get; set; } - public NpgsqlRange?[] testFieldNumrangeArrayNullable { get; set; } - public NpgsqlRange?[] testFieldTsrangeArrayNullable { get; set; } + public bool?[] testFieldBoolArrayNullable { get; set; } + public sbyte?[] testFieldSByteArrayNullable { get; set; } + public short?[] testFieldShortArrayNullable { get; set; } + public int?[] testFieldIntArrayNullable { get; set; } + public long?[] testFielLongArrayNullable { get; set; } + public byte?[] testFieldByteArrayNullable { get; set; } + public ushort?[] testFieldUShortArrayNullable { get; set; } + public uint?[] testFieldUIntArrayNullable { get; set; } + public ulong?[] testFieldULongArrayNullable { get; set; } + public double?[] testFieldDoubleArrayNullable { get; set; } + public float?[] testFieldFloatArrayNullable { get; set; } + public decimal?[] testFieldDecimalArrayNullable { get; set; } + public TimeSpan?[] testFieldTimeSpanArrayNullable { get; set; } + public DateTime?[] testFieldDateTimeArrayNullable { get; set; } + public Guid?[] testFieldGuidArrayNullable { get; set; } + public NpgsqlPoint?[] testFieldNpgsqlPointArrayNullable { get; set; } + public NpgsqlLine?[] testFieldNpgsqlLineArrayNullable { get; set; } + public NpgsqlLSeg?[] testFieldNpgsqlLSegArrayNullable { get; set; } + public NpgsqlBox?[] testFieldNpgsqlBoxArrayNullable { get; set; } + public NpgsqlPath?[] testFieldNpgsqlPathArrayNullable { get; set; } + public NpgsqlPolygon?[] testFieldNpgsqlPolygonArrayNullable { get; set; } + public NpgsqlCircle?[] testFieldNpgsqlCircleArrayNullable { get; set; } + public (IPAddress Address, int Subnet)?[] testFieldCidrArrayNullable { get; set; } + public NpgsqlRange?[] testFieldInt4rangeArrayNullable { get; set; } + public NpgsqlRange?[] testFieldInt8rangeArrayNullable { get; set; } + public NpgsqlRange?[] testFieldNumrangeArrayNullable { get; set; } + public NpgsqlRange?[] testFieldTsrangeArrayNullable { get; set; } - public BitArray[] testFieldBitArrayArray { get; set; } - public IPAddress[] testFieldInetArray { get; set; } - public PhysicalAddress[] testFieldMacaddrArray { get; set; } - public JToken[] testFieldJTokenArray { get; set; } - public JObject[] testFieldJObjectArray { get; set; } - public JArray[] testFieldJArrayArray { get; set; } - public Dictionary[] testFieldHStoreArray { get; set; } - public PostgisPoint[] testFieldPostgisPointArray { get; set; } - public PostgisLineString[] testFieldPostgisLineStringArray { get; set; } - public PostgisPolygon[] testFieldPostgisPolygonArray { get; set; } - public PostgisMultiPoint[] testFieldPostgisMultiPointArray { get; set; } - public PostgisMultiLineString[] testFieldPostgisPostgisMultiLineStringArray { get; set; } - public PostgisMultiPolygon[] testFieldPostgisPostgisMultiPolygonArray { get; set; } - public PostgisGeometry[] testFieldPostgisGeometryArray { get; set; } - public PostgisGeometryCollection[] testFieldPostgisGeometryCollectionArray { get; set; } + public BitArray[] testFieldBitArrayArray { get; set; } + public IPAddress[] testFieldInetArray { get; set; } + public PhysicalAddress[] testFieldMacaddrArray { get; set; } + public JToken[] testFieldJTokenArray { get; set; } + public JObject[] testFieldJObjectArray { get; set; } + public JArray[] testFieldJArrayArray { get; set; } + public Dictionary[] testFieldHStoreArray { get; set; } + public PostgisPoint[] testFieldPostgisPointArray { get; set; } + public PostgisLineString[] testFieldPostgisLineStringArray { get; set; } + public PostgisPolygon[] testFieldPostgisPolygonArray { get; set; } + public PostgisMultiPoint[] testFieldPostgisMultiPointArray { get; set; } + public PostgisMultiLineString[] testFieldPostgisPostgisMultiLineStringArray { get; set; } + public PostgisMultiPolygon[] testFieldPostgisPostgisMultiPolygonArray { get; set; } + public PostgisGeometry[] testFieldPostgisGeometryArray { get; set; } + public PostgisGeometryCollection[] testFieldPostgisGeometryCollectionArray { get; set; } - public TableAllTypeEnumType1[] testFieldEnum1Array { get; set; } - public TableAllTypeEnumType1?[] testFieldEnum1ArrayNullable { get; set; } - public TableAllTypeEnumType2[] testFieldEnum2Array { get; set; } - public TableAllTypeEnumType2?[] testFieldEnum2ArrayNullable { get; set; } - } + public TableAllTypeEnumType1[] testFieldEnum1Array { get; set; } + public TableAllTypeEnumType1?[] testFieldEnum1ArrayNullable { get; set; } + public TableAllTypeEnumType2[] testFieldEnum2Array { get; set; } + public TableAllTypeEnumType2?[] testFieldEnum2ArrayNullable { get; set; } + } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLDbFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLDbFirstTest.cs index 52aa48bc..f6c823c4 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLDbFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLDbFirstTest.cs @@ -2,20 +2,24 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.PostgreSQL { - public class PostgreSQLDbFirstTest { - [Fact] - public void GetDatabases() { +namespace FreeSql.Tests.PostgreSQL +{ + public class PostgreSQLDbFirstTest + { + [Fact] + public void GetDatabases() + { - var t1 = g.pgsql.DbFirst.GetDatabases(); + var t1 = g.pgsql.DbFirst.GetDatabases(); - } + } - [Fact] - public void GetTablesByDatabase() { + [Fact] + public void GetTablesByDatabase() + { - var t2 = g.pgsql.DbFirst.GetTablesByDatabase(g.pgsql.DbFirst.GetDatabases()[1]); + var t2 = g.pgsql.DbFirst.GetTablesByDatabase(g.pgsql.DbFirst.GetDatabases()[1]); - } - } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/ConvertTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/ConvertTest.cs index 02c98b7c..2a61c16a 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/ConvertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/ConvertTest.cs @@ -4,143 +4,166 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQLExpression { - public class ConvertTest { +namespace FreeSql.Tests.PostgreSQLExpression +{ + public class ConvertTest + { - ISelect select => g.pgsql.Select(); + ISelect select => g.pgsql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void ToBoolean() { - var data = new List(); - data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); - data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); - } - [Fact] - public void ToByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); - data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); - } - [Fact] - public void ToChar() { - var data = new List(); - //data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); - //data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); - } - [Fact] - public void ToDateTime() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); - } - [Fact] - public void ToDecimal() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToDouble() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt32() { - var data = new List(); - data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); - data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToSByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); - data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); - } - [Fact] - public void ToSingle() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); - data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); - } - [Fact] - public void ToUInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt32() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); - } + [Fact] + public void ToBoolean() + { + var data = new List(); + data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); + data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); + } + [Fact] + public void ToByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); + data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); + } + [Fact] + public void ToChar() + { + var data = new List(); + //data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); + //data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); + } + [Fact] + public void ToDateTime() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); + } + [Fact] + public void ToDecimal() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToDouble() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt32() + { + var data = new List(); + data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); + data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToSByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); + data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); + } + [Fact] + public void ToSingle() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); + data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); + } + [Fact] + public void ToUInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt32() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); + } - [Fact] - public void Guid_Parse() { - var data = new List(); - data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); - } + [Fact] + public void Guid_Parse() + { + var data = new List(); + data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); + } - [Fact] - public void Guid_NewGuid() { - var data = new List(); - //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); - } + [Fact] + public void Guid_NewGuid() + { + var data = new List(); + //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); + } - [Fact] - public void Random() { - var data = new List(); - data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); - data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); - } - } + [Fact] + public void Random() + { + var data = new List(); + data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); + data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/DateTimeTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/DateTimeTest.cs index ee70bad6..d99dd64c 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/DateTimeTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/DateTimeTest.cs @@ -4,664 +4,703 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQLExpression { - public class DateTimeTest { - - ISelect select => g.pgsql.Select(); - - [Table(Name = "tb_topic111333")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - [Table(Name = "TestTypeInfo333")] - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - public DateTime Time { get; set; } - } - [Table(Name = "TestTypeParentInfo23123")] - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - public DateTime Time2 { get; set; } - } - [Fact] - public void Now() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void UtcNow() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void Date() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) - } - [Fact] - public void TimeOfDay() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) - } - [Fact] - public void DayOfWeek() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) - } - [Fact] - public void Day() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) - } - [Fact] - public void DayOfYear() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) - } - [Fact] - public void Month() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (month(a.`CreateTime`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (month(a__Type.`Time`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (month(a__Type__Parent.`Time2`) > month(now())) - } - [Fact] - public void Year() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (year(a.`CreateTime`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (year(a__Type.`Time`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (year(a__Type__Parent.`Time2`) > year(now())) - } - [Fact] - public void Hour() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (hour(a.`CreateTime`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (hour(a__Type.`Time`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) - } - [Fact] - public void Minute() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (minute(a.`CreateTime`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (minute(a__Type.`Time`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) - } - [Fact] - public void Second() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (second(a.`CreateTime`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (second(a__Type.`Time`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (second(a__Type__Parent.`Time2`) > second(now())) - } - [Fact] - public void Millisecond() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) - } - [Fact] - public void AddDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) - } - [Fact] - public void AddHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) - } - [Fact] - public void AddMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) - } - [Fact] - public void AddMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) - } - [Fact] - public void AddMonths() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) - } - [Fact] - public void AddSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) - } - [Fact] - public void AddTicks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) - } - [Fact] - public void AddYears() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a."id", a."clicks", a."typeguid", a."title", a."createtime" - //FROM "tb_topic111333" a - //WHERE ((((extract(epoch from (a."createtime")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) - - //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" - //FROM "tb_topic111333" a - //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" - //WHERE ((((extract(epoch from (a__Type."time")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) - - //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" - //FROM "tb_topic111333" a - //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" - //LEFT JOIN "testtypeparentinfo23123" a__Type__Parent ON a__Type__Parent."id" = a__Type."parentid" - //WHERE ((((extract(epoch from (a__Type__Parent."time2")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) - data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a."id", a."clicks", a."typeguid", a."title", a."createtime" - //FROM "tb_topic111333" a - //WHERE (((a."createtime")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") - - //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" - //FROM "tb_topic111333" a - //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" - //WHERE (((a__Type."time")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") - - //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" - //FROM "tb_topic111333" a - //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" - //LEFT JOIN "testtypeparentinfo23123" a__Type__Parent ON a__Type__Parent."id" = a__Type."parentid" - //WHERE (((a__Type__Parent."time2")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") - } - [Fact] - public void _ЧͬSubtract() { - var data = new List(); - data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a."id", a."clicks", a."typeguid", a."title", a."createtime" - //FROM "tb_topic111333" a - //WHERE ((((extract(epoch from (a."createtime")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) - - //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" - //FROM "tb_topic111333" a - //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" - //WHERE ((((extract(epoch from (a__Type."time")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) - - //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" - //FROM "tb_topic111333" a - //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" - //LEFT JOIN "testtypeparentinfo23123" a__Type__Parent ON a__Type__Parent."id" = a__Type."parentid" - //WHERE ((((extract(epoch from (a__Type__Parent."time2")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) - data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a."id", a."clicks", a."typeguid", a."title", a."createtime" - //FROM "tb_topic111333" a - //WHERE (((a."createtime")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") - - //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" - //FROM "tb_topic111333" a - //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" - //WHERE (((a__Type."time")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") - - //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" - //FROM "tb_topic111333" a - //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" - //LEFT JOIN "testtypeparentinfo23123" a__Type__Parent ON a__Type__Parent."id" = a__Type."parentid" - //WHERE (((a__Type__Parent."time2")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) - } - - [Fact] - public void DateTime_Compare() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((a.`CreateTime`) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) - } - [Fact] - public void DateTime_DaysInMonth() { - var data = new List(); - data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) - } - [Fact] - public void DateTime_Equals() { - var data = new List(); - data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void DateTime_IsLeapYear() { - var data = new List(); - data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) - } - [Fact] - public void DateTime_Parse() { - var data = new List(); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) - } - } +namespace FreeSql.Tests.PostgreSQLExpression +{ + public class DateTimeTest + { + + ISelect select => g.pgsql.Select(); + + [Table(Name = "tb_topic111333")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + [Table(Name = "TestTypeInfo333")] + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + public DateTime Time { get; set; } + } + [Table(Name = "TestTypeParentInfo23123")] + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + public DateTime Time2 { get; set; } + } + [Fact] + public void Now() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void UtcNow() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void Date() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) + } + [Fact] + public void TimeOfDay() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) + } + [Fact] + public void DayOfWeek() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) + } + [Fact] + public void Day() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) + } + [Fact] + public void DayOfYear() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) + } + [Fact] + public void Month() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (month(a.`CreateTime`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (month(a__Type.`Time`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (month(a__Type__Parent.`Time2`) > month(now())) + } + [Fact] + public void Year() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (year(a.`CreateTime`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (year(a__Type.`Time`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (year(a__Type__Parent.`Time2`) > year(now())) + } + [Fact] + public void Hour() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (hour(a.`CreateTime`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (hour(a__Type.`Time`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) + } + [Fact] + public void Minute() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (minute(a.`CreateTime`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (minute(a__Type.`Time`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) + } + [Fact] + public void Second() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (second(a.`CreateTime`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (second(a__Type.`Time`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (second(a__Type__Parent.`Time2`) > second(now())) + } + [Fact] + public void Millisecond() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) + } + [Fact] + public void AddDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) + } + [Fact] + public void AddHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) + } + [Fact] + public void AddMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) + } + [Fact] + public void AddMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) + } + [Fact] + public void AddMonths() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) + } + [Fact] + public void AddSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) + } + [Fact] + public void AddTicks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) + } + [Fact] + public void AddYears() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a."id", a."clicks", a."typeguid", a."title", a."createtime" + //FROM "tb_topic111333" a + //WHERE ((((extract(epoch from (a."createtime")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) + + //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" + //FROM "tb_topic111333" a + //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" + //WHERE ((((extract(epoch from (a__Type."time")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) + + //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" + //FROM "tb_topic111333" a + //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" + //LEFT JOIN "testtypeparentinfo23123" a__Type__Parent ON a__Type__Parent."id" = a__Type."parentid" + //WHERE ((((extract(epoch from (a__Type__Parent."time2")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) + data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a."id", a."clicks", a."typeguid", a."title", a."createtime" + //FROM "tb_topic111333" a + //WHERE (((a."createtime")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") + + //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" + //FROM "tb_topic111333" a + //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" + //WHERE (((a__Type."time")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") + + //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" + //FROM "tb_topic111333" a + //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" + //LEFT JOIN "testtypeparentinfo23123" a__Type__Parent ON a__Type__Parent."id" = a__Type."parentid" + //WHERE (((a__Type__Parent."time2")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") + } + [Fact] + public void _ЧͬSubtract() + { + var data = new List(); + data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a."id", a."clicks", a."typeguid", a."title", a."createtime" + //FROM "tb_topic111333" a + //WHERE ((((extract(epoch from (a."createtime")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) + + //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" + //FROM "tb_topic111333" a + //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" + //WHERE ((((extract(epoch from (a__Type."time")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) + + //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" + //FROM "tb_topic111333" a + //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" + //LEFT JOIN "testtypeparentinfo23123" a__Type__Parent ON a__Type__Parent."id" = a__Type."parentid" + //WHERE ((((extract(epoch from (a__Type__Parent."time2")::timestamp-(current_timestamp)::timestamp)*1000000))/1000000) > 0) + data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a."id", a."clicks", a."typeguid", a."title", a."createtime" + //FROM "tb_topic111333" a + //WHERE (((a."createtime")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") + + //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" + //FROM "tb_topic111333" a + //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" + //WHERE (((a__Type."time")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") + + //SELECT a."id", a."clicks", a."typeguid", a__Type."guid", a__Type."parentid", a__Type."name", a__Type."time", a."title", a."createtime" + //FROM "tb_topic111333" a + //LEFT JOIN "testtypeinfo333" a__Type ON a__Type."guid" = a."typeguid" + //LEFT JOIN "testtypeparentinfo23123" a__Type__Parent ON a__Type__Parent."id" = a__Type."parentid" + //WHERE (((a__Type__Parent."time2")::timestamp-((((1)*86400000000))||' microseconds')::interval) > a."createtime") + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) + } + + [Fact] + public void DateTime_Compare() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((a.`CreateTime`) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) + } + [Fact] + public void DateTime_DaysInMonth() + { + var data = new List(); + data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) + } + [Fact] + public void DateTime_Equals() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void DateTime_IsLeapYear() + { + var data = new List(); + data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) + } + [Fact] + public void DateTime_Parse() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/MathTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/MathTest.cs index 731fa99a..edc58bd3 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/MathTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/MathTest.cs @@ -4,129 +4,153 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQLExpression { - public class MathTest { +namespace FreeSql.Tests.PostgreSQLExpression +{ + public class MathTest + { - ISelect select => g.pgsql.Select(); + ISelect select => g.pgsql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void PI() { - var data = new List(); - data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); - } - [Fact] - public void Abs() { - var data = new List(); - data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Sign() { - var data = new List(); - data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Floor() { - var data = new List(); - data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); - } - [Fact] - public void Ceiling() { - var data = new List(); - data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Round() { - var data = new List(); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); - } - [Fact] - public void Exp() { - var data = new List(); - data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log() { - var data = new List(); - //data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log10() { - var data = new List(); - //data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Pow() { - var data = new List(); - data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sqrt() { - var data = new List(); - data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Cos() { - var data = new List(); - data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sin() { - var data = new List(); - data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Tan() { - var data = new List(); - data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Acos() { - var data = new List(); - //data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Asin() { - var data = new List(); - //data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan() { - var data = new List(); - data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan2() { - var data = new List(); - data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Truncate() { - var data = new List(); - data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); - } - } + [Fact] + public void PI() + { + var data = new List(); + data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); + } + [Fact] + public void Abs() + { + var data = new List(); + data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Sign() + { + var data = new List(); + data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Floor() + { + var data = new List(); + data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); + } + [Fact] + public void Ceiling() + { + var data = new List(); + data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Round() + { + var data = new List(); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); + } + [Fact] + public void Exp() + { + var data = new List(); + data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log() + { + var data = new List(); + //data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log10() + { + var data = new List(); + //data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Pow() + { + var data = new List(); + data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sqrt() + { + var data = new List(); + data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Cos() + { + var data = new List(); + data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sin() + { + var data = new List(); + data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Tan() + { + var data = new List(); + data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Acos() + { + var data = new List(); + //data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Asin() + { + var data = new List(); + //data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan() + { + var data = new List(); + data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan2() + { + var data = new List(); + data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Truncate() + { + var data = new List(); + data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/OtherTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/OtherTest.cs index aa45e936..6a31499a 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/OtherTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/OtherTest.cs @@ -12,286 +12,294 @@ using System.Net; using System.Net.NetworkInformation; using Xunit; -namespace FreeSql.Tests.PostgreSQLExpression { - public class OtherTest { +namespace FreeSql.Tests.PostgreSQLExpression +{ + public class OtherTest + { - ISelect select => g.pgsql.Select(); + ISelect select => g.pgsql.Select(); - public OtherTest() { - NpgsqlConnection.GlobalTypeMapper.UseLegacyPostgis(); - } + public OtherTest() + { + NpgsqlConnection.GlobalTypeMapper.UseLegacyPostgis(); + } - [Fact] - public void Boolean() { - var t1 = select.Where(a => a.testFieldBool == true).ToList(); - var t2 = select.Where(a => a.testFieldBool != true).ToList(); - var t3 = select.Where(a => a.testFieldBool == false).ToList(); - var t4 = select.Where(a => !a.testFieldBool).ToList(); - var t5 = select.Where(a => a.testFieldBool).ToList(); + [Fact] + public void Boolean() + { + var t1 = select.Where(a => a.testFieldBool == true).ToList(); + var t2 = select.Where(a => a.testFieldBool != true).ToList(); + var t3 = select.Where(a => a.testFieldBool == false).ToList(); + var t4 = select.Where(a => !a.testFieldBool).ToList(); + var t5 = select.Where(a => a.testFieldBool).ToList(); - var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList(); - var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); - var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); - var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); - var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList(); - } + var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList(); + var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); + var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); + var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); + var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList(); + } - [Fact] - public void Array() { - //g.pgsql.Aop.CurdAfter = (s, e) => { - // Trace.WriteLine(e.CurdType + ": " + e.ElapsedMilliseconds + "ms " + e.Sql.Replace("\n", "")); - //}; - IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); - var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); + [Fact] + public void Array() + { + //g.pgsql.Aop.CurdAfter = (s, e) => { + // Trace.WriteLine(e.CurdType + ": " + e.ElapsedMilliseconds + "ms " + e.Sql.Replace("\n", "")); + //}; + IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); + var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); - var sql1 = select.Where(a => a.testFieldIntArray.Contains(1)).ToList(); - var sql2 = select.Where(a => a.testFieldIntArray.Contains(1) == false).ToList(); + var sql1 = select.Where(a => a.testFieldIntArray.Contains(1)).ToList(); + var sql2 = select.Where(a => a.testFieldIntArray.Contains(1) == false).ToList(); - //in not in - var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); - var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + //in not in + var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); + var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var inarray = new[] { 1, 2, 3 }; - var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToSql(); - var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToSql(); - var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToSql(); + var inarray = new[] { 1, 2, 3 }; + var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToSql(); + var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToSql(); + var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToSql(); - //in not in - var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); - var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + //in not in + var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); + var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); - var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); - var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); + var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); + var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); + var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); - var inarray2 = new List() { 1, 2, 3 }; - var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); - var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); - var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); + var inarray2 = new List() { 1, 2, 3 }; + var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); + var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); + var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); - var sql1111112 = select.ToList(a => inarray); - var sql1111113 = select.ToList(a => a.testFieldIntArray); + var sql1111112 = select.ToList(a => inarray); + var sql1111113 = select.ToList(a => a.testFieldIntArray); - var sql3 = select.Where(a => a.testFieldIntArray.Any()).ToList(); - var sql4 = select.Where(a => a.testFieldIntArray.Any() == false).ToList(); + var sql3 = select.Where(a => a.testFieldIntArray.Any()).ToList(); + var sql4 = select.Where(a => a.testFieldIntArray.Any() == false).ToList(); - var sql5 = select.ToList(a => a.testFieldIntArray.Concat(new[] { 1, 2, 3 })); + var sql5 = select.ToList(a => a.testFieldIntArray.Concat(new[] { 1, 2, 3 })); - var sql6 = select.Where(a => a.testFieldIntArray.GetLength(1) > 0).ToList(); - var sql7 = select.Where(a => a.testFieldIntArray.GetLongLength(1) > 0).ToList(); - var sql8 = select.Where(a => a.testFieldIntArray.Length > 0).ToList(); - var sql9 = select.Where(a => a.testFieldIntArray.Count() > 0).ToList(); - } + var sql6 = select.Where(a => a.testFieldIntArray.GetLength(1) > 0).ToList(); + var sql7 = select.Where(a => a.testFieldIntArray.GetLongLength(1) > 0).ToList(); + var sql8 = select.Where(a => a.testFieldIntArray.Length > 0).ToList(); + var sql9 = select.Where(a => a.testFieldIntArray.Count() > 0).ToList(); + } - [Fact] - public void Jsonb() { + [Fact] + public void Jsonb() + { - var sql1 = select.Where(a => a.testFieldJToken.Contains(JToken.Parse("{a:1}"))).ToList(); - var sql2 = select.Where(a => a.testFieldJToken.Contains(JToken.Parse("{a:1}")) == false).ToList(); - var sql111 = select.Where(a => a.testFieldJToken.Contains("{a:1}")).ToList(); - var sql222 = select.Where(a => a.testFieldJToken.Contains("{a:1}") == false).ToList(); + var sql1 = select.Where(a => a.testFieldJToken.Contains(JToken.Parse("{a:1}"))).ToList(); + var sql2 = select.Where(a => a.testFieldJToken.Contains(JToken.Parse("{a:1}")) == false).ToList(); + var sql111 = select.Where(a => a.testFieldJToken.Contains("{a:1}")).ToList(); + var sql222 = select.Where(a => a.testFieldJToken.Contains("{a:1}") == false).ToList(); - var sql3 = select.Where(a => a.testFieldJObject.ContainsKey("a")).ToList(); - var sql4 = select.Where(a => a.testFieldJObject.ContainsKey("a") == false).ToList(); + var sql3 = select.Where(a => a.testFieldJObject.ContainsKey("a")).ToList(); + var sql4 = select.Where(a => a.testFieldJObject.ContainsKey("a") == false).ToList(); - var sql5 = select.Where(a => a.testFieldJArray.Contains(1)).ToList(); - var sql6 = select.Where(a => a.testFieldJArray.Contains(1) == false).ToList(); - var sql555 = select.Where(a => a.testFieldJArray.Contains(1)).ToList(); - var sql666 = select.Where(a => a.testFieldJArray.Contains(1) == false).ToList(); + var sql5 = select.Where(a => a.testFieldJArray.Contains(1)).ToList(); + var sql6 = select.Where(a => a.testFieldJArray.Contains(1) == false).ToList(); + var sql555 = select.Where(a => a.testFieldJArray.Contains(1)).ToList(); + var sql666 = select.Where(a => a.testFieldJArray.Contains(1) == false).ToList(); - //var sql7 = select.Where(a => a.testFieldJToken.Any()).ToList(); - //var sql8 = select.Where(a => a.testFieldJToken.Any() == false).ToList(); + //var sql7 = select.Where(a => a.testFieldJToken.Any()).ToList(); + //var sql8 = select.Where(a => a.testFieldJToken.Any() == false).ToList(); - var sql9 = select.Where(a => a.testFieldJArray.Any()).ToList(); - var sql10 = select.Where(a => a.testFieldJArray.Any() == false).ToList(); + var sql9 = select.Where(a => a.testFieldJArray.Any()).ToList(); + var sql10 = select.Where(a => a.testFieldJArray.Any() == false).ToList(); - //var sql11 = select.ToList(a => a.testFieldJToken.Concat(JToken.Parse("{a:1}"))); - //var sql12 = select.ToList(a => a.testFieldJObject.Concat(JToken.Parse("{a:1}"))); - //var sql13 = select.ToList(a => a.testFieldJArray.Concat(JToken.Parse("{a:1}"))); + //var sql11 = select.ToList(a => a.testFieldJToken.Concat(JToken.Parse("{a:1}"))); + //var sql12 = select.ToList(a => a.testFieldJObject.Concat(JToken.Parse("{a:1}"))); + //var sql13 = select.ToList(a => a.testFieldJArray.Concat(JToken.Parse("{a:1}"))); - //var sql14 = select.Where(a => a.testFieldJToken.Count() > 0).ToList(); - //var sql15 = select.Where(a => a.testFieldJObject.Count > 0).ToList(); - var sql16 = select.Where(a => a.testFieldJArray.Count() > 0).ToList(); - var sql17 = select.Where(a => a.testFieldJArray.LongCount() > 0).ToList(); - var sql18 = select.Where(a => a.testFieldJArray.Count > 0).ToList(); - } + //var sql14 = select.Where(a => a.testFieldJToken.Count() > 0).ToList(); + //var sql15 = select.Where(a => a.testFieldJObject.Count > 0).ToList(); + var sql16 = select.Where(a => a.testFieldJArray.Count() > 0).ToList(); + var sql17 = select.Where(a => a.testFieldJArray.LongCount() > 0).ToList(); + var sql18 = select.Where(a => a.testFieldJArray.Count > 0).ToList(); + } - [Fact] - public void HStore() { + [Fact] + public void HStore() + { - var sql1 = select.Where(a => a.testFieldHStore.ContainsKey("a")).ToList(); - var sql2 = select.Where(a => a.testFieldHStore.ContainsKey("a") == false).ToList(); - } + var sql1 = select.Where(a => a.testFieldHStore.ContainsKey("a")).ToList(); + var sql2 = select.Where(a => a.testFieldHStore.ContainsKey("a") == false).ToList(); + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - public bool testFieldBool { get; set; } - public sbyte testFieldSByte { get; set; } - public short testFieldShort { get; set; } - public int testFieldInt { get; set; } - public long testFieldLong { get; set; } - public byte testFieldByte { get; set; } - public ushort testFieldUShort { get; set; } - public uint testFieldUInt { get; set; } - public ulong testFieldULong { get; set; } - public double testFieldDouble { get; set; } - public float testFieldFloat { get; set; } - public decimal testFieldDecimal { get; set; } - public TimeSpan testFieldTimeSpan { get; set; } - public DateTime testFieldDateTime { get; set; } - public byte[] testFieldBytes { get; set; } - public string testFieldString { get; set; } - public Guid testFieldGuid { get; set; } - public NpgsqlPoint testFieldNpgsqlPoint { get; set; } - public NpgsqlLine testFieldNpgsqlLine { get; set; } - public NpgsqlLSeg testFieldNpgsqlLSeg { get; set; } - public NpgsqlBox testFieldNpgsqlBox { get; set; } - public NpgsqlPath testFieldNpgsqlPath { get; set; } - public NpgsqlPolygon testFieldNpgsqlPolygon { get; set; } - public NpgsqlCircle testFieldNpgsqlCircle { get; set; } - public (IPAddress Address, int Subnet) testFieldCidr { get; set; } - public NpgsqlRange testFieldInt4range { get; set; } - public NpgsqlRange testFieldInt8range { get; set; } - public NpgsqlRange testFieldNumrange { get; set; } - public NpgsqlRange testFieldTsrange { get; set; } + public bool testFieldBool { get; set; } + public sbyte testFieldSByte { get; set; } + public short testFieldShort { get; set; } + public int testFieldInt { get; set; } + public long testFieldLong { get; set; } + public byte testFieldByte { get; set; } + public ushort testFieldUShort { get; set; } + public uint testFieldUInt { get; set; } + public ulong testFieldULong { get; set; } + public double testFieldDouble { get; set; } + public float testFieldFloat { get; set; } + public decimal testFieldDecimal { get; set; } + public TimeSpan testFieldTimeSpan { get; set; } + public DateTime testFieldDateTime { get; set; } + public byte[] testFieldBytes { get; set; } + public string testFieldString { get; set; } + public Guid testFieldGuid { get; set; } + public NpgsqlPoint testFieldNpgsqlPoint { get; set; } + public NpgsqlLine testFieldNpgsqlLine { get; set; } + public NpgsqlLSeg testFieldNpgsqlLSeg { get; set; } + public NpgsqlBox testFieldNpgsqlBox { get; set; } + public NpgsqlPath testFieldNpgsqlPath { get; set; } + public NpgsqlPolygon testFieldNpgsqlPolygon { get; set; } + public NpgsqlCircle testFieldNpgsqlCircle { get; set; } + public (IPAddress Address, int Subnet) testFieldCidr { get; set; } + public NpgsqlRange testFieldInt4range { get; set; } + public NpgsqlRange testFieldInt8range { get; set; } + public NpgsqlRange testFieldNumrange { get; set; } + public NpgsqlRange testFieldTsrange { get; set; } - public bool? testFieldBoolNullable { get; set; } - public sbyte? testFieldSByteNullable { get; set; } - public short? testFieldShortNullable { get; set; } - public int? testFieldIntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? testFieldByteNullable { get; set; } - public ushort? testFieldUShortNullable { get; set; } - public uint? testFieldUIntNullable { get; set; } - public ulong? testFieldULongNullable { get; set; } - public double? testFieldDoubleNullable { get; set; } - public float? testFieldFloatNullable { get; set; } - public decimal? testFieldDecimalNullable { get; set; } - public TimeSpan? testFieldTimeSpanNullable { get; set; } - public DateTime? testFieldDateTimeNullable { get; set; } - public Guid? testFieldGuidNullable { get; set; } - public NpgsqlPoint? testFieldNpgsqlPointNullable { get; set; } - public NpgsqlLine? testFieldNpgsqlLineNullable { get; set; } - public NpgsqlLSeg? testFieldNpgsqlLSegNullable { get; set; } - public NpgsqlBox? testFieldNpgsqlBoxNullable { get; set; } - public NpgsqlPath? testFieldNpgsqlPathNullable { get; set; } - public NpgsqlPolygon? testFieldNpgsqlPolygonNullable { get; set; } - public NpgsqlCircle? testFieldNpgsqlCircleNullable { get; set; } - public (IPAddress Address, int Subnet)? testFieldCidrNullable { get; set; } - public NpgsqlRange? testFieldInt4rangeNullable { get; set; } - public NpgsqlRange? testFieldInt8rangeNullable { get; set; } - public NpgsqlRange? testFieldNumrangeNullable { get; set; } - public NpgsqlRange? testFieldTsrangeNullable { get; set; } + public bool? testFieldBoolNullable { get; set; } + public sbyte? testFieldSByteNullable { get; set; } + public short? testFieldShortNullable { get; set; } + public int? testFieldIntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? testFieldByteNullable { get; set; } + public ushort? testFieldUShortNullable { get; set; } + public uint? testFieldUIntNullable { get; set; } + public ulong? testFieldULongNullable { get; set; } + public double? testFieldDoubleNullable { get; set; } + public float? testFieldFloatNullable { get; set; } + public decimal? testFieldDecimalNullable { get; set; } + public TimeSpan? testFieldTimeSpanNullable { get; set; } + public DateTime? testFieldDateTimeNullable { get; set; } + public Guid? testFieldGuidNullable { get; set; } + public NpgsqlPoint? testFieldNpgsqlPointNullable { get; set; } + public NpgsqlLine? testFieldNpgsqlLineNullable { get; set; } + public NpgsqlLSeg? testFieldNpgsqlLSegNullable { get; set; } + public NpgsqlBox? testFieldNpgsqlBoxNullable { get; set; } + public NpgsqlPath? testFieldNpgsqlPathNullable { get; set; } + public NpgsqlPolygon? testFieldNpgsqlPolygonNullable { get; set; } + public NpgsqlCircle? testFieldNpgsqlCircleNullable { get; set; } + public (IPAddress Address, int Subnet)? testFieldCidrNullable { get; set; } + public NpgsqlRange? testFieldInt4rangeNullable { get; set; } + public NpgsqlRange? testFieldInt8rangeNullable { get; set; } + public NpgsqlRange? testFieldNumrangeNullable { get; set; } + public NpgsqlRange? testFieldTsrangeNullable { get; set; } - public BitArray testFieldBitArray { get; set; } - public IPAddress testFieldInet { get; set; } - public PhysicalAddress testFieldMacaddr { get; set; } - public JToken testFieldJToken { get; set; } - public JObject testFieldJObject { get; set; } - public JArray testFieldJArray { get; set; } - public Dictionary testFieldHStore { get; set; } - public PostgisPoint testFieldPostgisPoint { get; set; } - public PostgisLineString testFieldPostgisLineString { get; set; } - public PostgisPolygon testFieldPostgisPolygon { get; set; } - public PostgisMultiPoint testFieldPostgisMultiPoint { get; set; } - public PostgisMultiLineString testFieldPostgisPostgisMultiLineString { get; set; } - public PostgisMultiPolygon testFieldPostgisPostgisMultiPolygon { get; set; } - public PostgisGeometry testFieldPostgisGeometry { get; set; } - public PostgisGeometryCollection testFieldPostgisGeometryCollection { get; set; } + public BitArray testFieldBitArray { get; set; } + public IPAddress testFieldInet { get; set; } + public PhysicalAddress testFieldMacaddr { get; set; } + public JToken testFieldJToken { get; set; } + public JObject testFieldJObject { get; set; } + public JArray testFieldJArray { get; set; } + public Dictionary testFieldHStore { get; set; } + public PostgisPoint testFieldPostgisPoint { get; set; } + public PostgisLineString testFieldPostgisLineString { get; set; } + public PostgisPolygon testFieldPostgisPolygon { get; set; } + public PostgisMultiPoint testFieldPostgisMultiPoint { get; set; } + public PostgisMultiLineString testFieldPostgisPostgisMultiLineString { get; set; } + public PostgisMultiPolygon testFieldPostgisPostgisMultiPolygon { get; set; } + public PostgisGeometry testFieldPostgisGeometry { get; set; } + public PostgisGeometryCollection testFieldPostgisGeometryCollection { get; set; } - public TableAllTypeEnumType1 testFieldEnum1 { get; set; } - public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } - public TableAllTypeEnumType2 testFieldEnum2 { get; set; } - public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } + public TableAllTypeEnumType1 testFieldEnum1 { get; set; } + public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } + public TableAllTypeEnumType2 testFieldEnum2 { get; set; } + public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } - /* array */ - public bool[] testFieldBoolArray { get; set; } - public sbyte[] testFieldSByteArray { get; set; } - public short[] testFieldShortArray { get; set; } - public int[] testFieldIntArray { get; set; } - public long[] testFieldLongArray { get; set; } - public byte[] testFieldByteArray { get; set; } - public ushort[] testFieldUShortArray { get; set; } - public uint[] testFieldUIntArray { get; set; } - public ulong[] testFieldULongArray { get; set; } - public double[] testFieldDoubleArray { get; set; } - public float[] testFieldFloatArray { get; set; } - public decimal[] testFieldDecimalArray { get; set; } - public TimeSpan[] testFieldTimeSpanArray { get; set; } - public DateTime[] testFieldDateTimeArray { get; set; } - public byte[][] testFieldBytesArray { get; set; } - public string[] testFieldStringArray { get; set; } - public Guid[] testFieldGuidArray { get; set; } - public NpgsqlPoint[] testFieldNpgsqlPointArray { get; set; } - public NpgsqlLine[] testFieldNpgsqlLineArray { get; set; } - public NpgsqlLSeg[] testFieldNpgsqlLSegArray { get; set; } - public NpgsqlBox[] testFieldNpgsqlBoxArray { get; set; } - public NpgsqlPath[] testFieldNpgsqlPathArray { get; set; } - public NpgsqlPolygon[] testFieldNpgsqlPolygonArray { get; set; } - public NpgsqlCircle[] testFieldNpgsqlCircleArray { get; set; } - public (IPAddress Address, int Subnet)[] testFieldCidrArray { get; set; } - public NpgsqlRange[] testFieldInt4rangeArray { get; set; } - public NpgsqlRange[] testFieldInt8rangeArray { get; set; } - public NpgsqlRange[] testFieldNumrangeArray { get; set; } - public NpgsqlRange[] testFieldTsrangeArray { get; set; } + /* array */ + public bool[] testFieldBoolArray { get; set; } + public sbyte[] testFieldSByteArray { get; set; } + public short[] testFieldShortArray { get; set; } + public int[] testFieldIntArray { get; set; } + public long[] testFieldLongArray { get; set; } + public byte[] testFieldByteArray { get; set; } + public ushort[] testFieldUShortArray { get; set; } + public uint[] testFieldUIntArray { get; set; } + public ulong[] testFieldULongArray { get; set; } + public double[] testFieldDoubleArray { get; set; } + public float[] testFieldFloatArray { get; set; } + public decimal[] testFieldDecimalArray { get; set; } + public TimeSpan[] testFieldTimeSpanArray { get; set; } + public DateTime[] testFieldDateTimeArray { get; set; } + public byte[][] testFieldBytesArray { get; set; } + public string[] testFieldStringArray { get; set; } + public Guid[] testFieldGuidArray { get; set; } + public NpgsqlPoint[] testFieldNpgsqlPointArray { get; set; } + public NpgsqlLine[] testFieldNpgsqlLineArray { get; set; } + public NpgsqlLSeg[] testFieldNpgsqlLSegArray { get; set; } + public NpgsqlBox[] testFieldNpgsqlBoxArray { get; set; } + public NpgsqlPath[] testFieldNpgsqlPathArray { get; set; } + public NpgsqlPolygon[] testFieldNpgsqlPolygonArray { get; set; } + public NpgsqlCircle[] testFieldNpgsqlCircleArray { get; set; } + public (IPAddress Address, int Subnet)[] testFieldCidrArray { get; set; } + public NpgsqlRange[] testFieldInt4rangeArray { get; set; } + public NpgsqlRange[] testFieldInt8rangeArray { get; set; } + public NpgsqlRange[] testFieldNumrangeArray { get; set; } + public NpgsqlRange[] testFieldTsrangeArray { get; set; } - public bool?[] testFieldBoolArrayNullable { get; set; } - public sbyte?[] testFieldSByteArrayNullable { get; set; } - public short?[] testFieldShortArrayNullable { get; set; } - public int?[] testFieldIntArrayNullable { get; set; } - public long?[] testFielLongArrayNullable { get; set; } - public byte?[] testFieldByteArrayNullable { get; set; } - public ushort?[] testFieldUShortArrayNullable { get; set; } - public uint?[] testFieldUIntArrayNullable { get; set; } - public ulong?[] testFieldULongArrayNullable { get; set; } - public double?[] testFieldDoubleArrayNullable { get; set; } - public float?[] testFieldFloatArrayNullable { get; set; } - public decimal?[] testFieldDecimalArrayNullable { get; set; } - public TimeSpan?[] testFieldTimeSpanArrayNullable { get; set; } - public DateTime?[] testFieldDateTimeArrayNullable { get; set; } - public Guid?[] testFieldGuidArrayNullable { get; set; } - public NpgsqlPoint?[] testFieldNpgsqlPointArrayNullable { get; set; } - public NpgsqlLine?[] testFieldNpgsqlLineArrayNullable { get; set; } - public NpgsqlLSeg?[] testFieldNpgsqlLSegArrayNullable { get; set; } - public NpgsqlBox?[] testFieldNpgsqlBoxArrayNullable { get; set; } - public NpgsqlPath?[] testFieldNpgsqlPathArrayNullable { get; set; } - public NpgsqlPolygon?[] testFieldNpgsqlPolygonArrayNullable { get; set; } - public NpgsqlCircle?[] testFieldNpgsqlCircleArrayNullable { get; set; } - public (IPAddress Address, int Subnet)?[] testFieldCidrArrayNullable { get; set; } - public NpgsqlRange?[] testFieldInt4rangeArrayNullable { get; set; } - public NpgsqlRange?[] testFieldInt8rangeArrayNullable { get; set; } - public NpgsqlRange?[] testFieldNumrangeArrayNullable { get; set; } - public NpgsqlRange?[] testFieldTsrangeArrayNullable { get; set; } + public bool?[] testFieldBoolArrayNullable { get; set; } + public sbyte?[] testFieldSByteArrayNullable { get; set; } + public short?[] testFieldShortArrayNullable { get; set; } + public int?[] testFieldIntArrayNullable { get; set; } + public long?[] testFielLongArrayNullable { get; set; } + public byte?[] testFieldByteArrayNullable { get; set; } + public ushort?[] testFieldUShortArrayNullable { get; set; } + public uint?[] testFieldUIntArrayNullable { get; set; } + public ulong?[] testFieldULongArrayNullable { get; set; } + public double?[] testFieldDoubleArrayNullable { get; set; } + public float?[] testFieldFloatArrayNullable { get; set; } + public decimal?[] testFieldDecimalArrayNullable { get; set; } + public TimeSpan?[] testFieldTimeSpanArrayNullable { get; set; } + public DateTime?[] testFieldDateTimeArrayNullable { get; set; } + public Guid?[] testFieldGuidArrayNullable { get; set; } + public NpgsqlPoint?[] testFieldNpgsqlPointArrayNullable { get; set; } + public NpgsqlLine?[] testFieldNpgsqlLineArrayNullable { get; set; } + public NpgsqlLSeg?[] testFieldNpgsqlLSegArrayNullable { get; set; } + public NpgsqlBox?[] testFieldNpgsqlBoxArrayNullable { get; set; } + public NpgsqlPath?[] testFieldNpgsqlPathArrayNullable { get; set; } + public NpgsqlPolygon?[] testFieldNpgsqlPolygonArrayNullable { get; set; } + public NpgsqlCircle?[] testFieldNpgsqlCircleArrayNullable { get; set; } + public (IPAddress Address, int Subnet)?[] testFieldCidrArrayNullable { get; set; } + public NpgsqlRange?[] testFieldInt4rangeArrayNullable { get; set; } + public NpgsqlRange?[] testFieldInt8rangeArrayNullable { get; set; } + public NpgsqlRange?[] testFieldNumrangeArrayNullable { get; set; } + public NpgsqlRange?[] testFieldTsrangeArrayNullable { get; set; } - public BitArray[] testFieldBitArrayArray { get; set; } - public IPAddress[] testFieldInetArray { get; set; } - public PhysicalAddress[] testFieldMacaddrArray { get; set; } - public JToken[] testFieldJTokenArray { get; set; } - public JObject[] testFieldJObjectArray { get; set; } - public JArray[] testFieldJArrayArray { get; set; } - public Dictionary[] testFieldHStoreArray { get; set; } - public PostgisPoint[] testFieldPostgisPointArray { get; set; } - public PostgisLineString[] testFieldPostgisLineStringArray { get; set; } - public PostgisPolygon[] testFieldPostgisPolygonArray { get; set; } - public PostgisMultiPoint[] testFieldPostgisMultiPointArray { get; set; } - public PostgisMultiLineString[] testFieldPostgisPostgisMultiLineStringArray { get; set; } - public PostgisMultiPolygon[] testFieldPostgisPostgisMultiPolygonArray { get; set; } - public PostgisGeometry[] testFieldPostgisGeometryArray { get; set; } - public PostgisGeometryCollection[] testFieldPostgisGeometryCollectionArray { get; set; } + public BitArray[] testFieldBitArrayArray { get; set; } + public IPAddress[] testFieldInetArray { get; set; } + public PhysicalAddress[] testFieldMacaddrArray { get; set; } + public JToken[] testFieldJTokenArray { get; set; } + public JObject[] testFieldJObjectArray { get; set; } + public JArray[] testFieldJArrayArray { get; set; } + public Dictionary[] testFieldHStoreArray { get; set; } + public PostgisPoint[] testFieldPostgisPointArray { get; set; } + public PostgisLineString[] testFieldPostgisLineStringArray { get; set; } + public PostgisPolygon[] testFieldPostgisPolygonArray { get; set; } + public PostgisMultiPoint[] testFieldPostgisMultiPointArray { get; set; } + public PostgisMultiLineString[] testFieldPostgisPostgisMultiLineStringArray { get; set; } + public PostgisMultiPolygon[] testFieldPostgisPostgisMultiPolygonArray { get; set; } + public PostgisGeometry[] testFieldPostgisGeometryArray { get; set; } + public PostgisGeometryCollection[] testFieldPostgisGeometryCollectionArray { get; set; } - public TableAllTypeEnumType1[] testFieldEnum1Array { get; set; } - public TableAllTypeEnumType1?[] testFieldEnum1ArrayNullable { get; set; } - public TableAllTypeEnumType2[] testFieldEnum2Array { get; set; } - public TableAllTypeEnumType2?[] testFieldEnum2ArrayNullable { get; set; } - } + public TableAllTypeEnumType1[] testFieldEnum1Array { get; set; } + public TableAllTypeEnumType1?[] testFieldEnum1ArrayNullable { get; set; } + public TableAllTypeEnumType2[] testFieldEnum2Array { get; set; } + public TableAllTypeEnumType2?[] testFieldEnum2ArrayNullable { get; set; } + } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/StringTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/StringTest.cs index 16ad0aee..b4976d92 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/StringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/StringTest.cs @@ -4,692 +4,716 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQLExpression { - public class StringTest { - - ISelect select => g.pgsql.Select(); - - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - class TestEqualsGuid { - public Guid id { get; set; } - } - - [Fact] - public void Equals__() { - var list = new List(); - list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); - list.Add(g.pgsql.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); - } - - - [Fact] - public void Empty() { - var data = new List(); - data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ifnull(a.`Title`, '') = '') - } - - [Fact] - public void StartsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) - list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) - } - [Fact] - public void EndsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) - } - [Fact] - public void Contains() { - var list = new List(); - list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) - } - [Fact] - public void ToLower() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void ToUpper() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void Substring() { - var data = new List(); - data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) - } - [Fact] - public void Length() { - var data = new List(); - data.Add(select.Where(a => a.Title.Length == 0).ToList()); - data.Add(select.Where(a => a.Title.Length == 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); - data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) - } - [Fact] - public void IndexOf() { - var data = new List(); - data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) - } - [Fact] - public void PadLeft() { - var data = new List(); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void PadRight() { - var data = new List(); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void Trim() { - var data = new List(); - data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void TrimStart() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) - } - [Fact] - public void TrimEnd() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void Replace() { - var data = new List(); - data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) - } - - [Fact] - public void string_IsNullOrEmpty() { - var data = new List(); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); - data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); - } - } +namespace FreeSql.Tests.PostgreSQLExpression +{ + public class StringTest + { + + ISelect select => g.pgsql.Select(); + + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + class TestEqualsGuid + { + public Guid id { get; set; } + } + + [Fact] + public void Equals__() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); + list.Add(g.pgsql.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); + } + + + [Fact] + public void Empty() + { + var data = new List(); + data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ifnull(a.`Title`, '') = '') + } + + [Fact] + public void StartsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) + list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) + } + [Fact] + public void EndsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) + } + [Fact] + public void Contains() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) + } + [Fact] + public void ToLower() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void ToUpper() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void Substring() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) + } + [Fact] + public void Length() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Length == 0).ToList()); + data.Add(select.Where(a => a.Title.Length == 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); + data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) + } + [Fact] + public void IndexOf() + { + var data = new List(); + data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) + } + [Fact] + public void PadLeft() + { + var data = new List(); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void PadRight() + { + var data = new List(); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void Trim() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void TrimStart() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) + } + [Fact] + public void TrimEnd() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void Replace() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) + } + + [Fact] + public void string_IsNullOrEmpty() + { + var data = new List(); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); + data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/TimeSpanTest.cs b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/TimeSpanTest.cs index 320cca13..3ff2ad7a 100644 --- a/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/TimeSpanTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/PostgreSQL/PostgreSQLExpression/TimeSpanTest.cs @@ -4,257 +4,290 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.PostgreSQLExpression { - public class TimeSpanTest { +namespace FreeSql.Tests.PostgreSQLExpression +{ + public class TimeSpanTest + { - ISelect select => g.pgsql.Select(); + ISelect select => g.pgsql.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } - [Fact] - public void Zero() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) - } - [Fact] - public void Days() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) - } - [Fact] - public void Hours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) - } - [Fact] - public void Milliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) - } - [Fact] - public void Minutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) - } - [Fact] - public void Seconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) - } - [Fact] - public void TotalDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) - } - [Fact] - public void TotalHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) - } - [Fact] - public void TotalMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) - } - [Fact] - public void TotalMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) - } - [Fact] - public void TotalSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') - } + public List Types { get; set; } + } + [Fact] + public void Zero() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) + } + [Fact] + public void Days() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) + } + [Fact] + public void Hours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) + } + [Fact] + public void Milliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) + } + [Fact] + public void Minutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) + } + [Fact] + public void Seconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) + } + [Fact] + public void TotalDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) + } + [Fact] + public void TotalHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) + } + [Fact] + public void TotalMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) + } + [Fact] + public void TotalMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) + } + [Fact] + public void TotalSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') + } - [Fact] - public void TimeSpan_Compare() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void TimeSpan_Equals() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromDays() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromHours() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) - } - [Fact] - public void TimeSpan_FromMilliseconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) - } - [Fact] - public void TimeSpan_FromMinutes() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) - } - [Fact] - public void TimeSpan_FromSeconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) - } - [Fact] - public void TimeSpan_FromTicks() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) - } - [Fact] - public void TimeSpan_Parse() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) - } - } + [Fact] + public void TimeSpan_Compare() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void TimeSpan_Equals() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromDays() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromHours() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) + } + [Fact] + public void TimeSpan_FromMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) + } + [Fact] + public void TimeSpan_FromMinutes() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) + } + [Fact] + public void TimeSpan_FromSeconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) + } + [Fact] + public void TimeSpan_FromTicks() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) + } + [Fact] + public void TimeSpan_Parse() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerDeleteTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerDeleteTest.cs index 5b11406e..5a5bbcb8 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerDeleteTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerDeleteTest.cs @@ -5,100 +5,108 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServer { - [Collection("SqlServerCollection")] - public class SqlServerDeleteTest - { - SqlServerFixture _sqlserverFixture; +namespace FreeSql.Tests.SqlServer +{ + [Collection("SqlServerCollection")] + public class SqlServerDeleteTest + { + SqlServerFixture _sqlserverFixture; - public SqlServerDeleteTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public SqlServerDeleteTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - IDelete delete => _sqlserverFixture.SqlServer.Delete(); //�������� + IDelete delete => _sqlserverFixture.SqlServer.Delete(); //�������� - [Table(Name = "tb_topic22211")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } + [Table(Name = "tb_topic22211")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void Dywhere() { - Assert.Null(_sqlserverFixture.SqlServer.Delete().ToSql()); - var sql = _sqlserverFixture.SqlServer.Delete(new[] { 1, 2 }).ToSql(); - Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1 OR [Id] = 2)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(_sqlserverFixture.SqlServer.Delete().ToSql()); + var sql = _sqlserverFixture.SqlServer.Delete(new[] { 1, 2 }).ToSql(); + Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1 OR [Id] = 2)", sql); - sql = _sqlserverFixture.SqlServer.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); - Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql); + sql = _sqlserverFixture.SqlServer.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); + Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql); - sql = _sqlserverFixture.SqlServer.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); - Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1 OR [Id] = 2)", sql); + sql = _sqlserverFixture.SqlServer.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); + Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1 OR [Id] = 2)", sql); - sql = _sqlserverFixture.SqlServer.Delete(new { id = 1 }).ToSql(); - Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql); - } + sql = _sqlserverFixture.SqlServer.Delete(new { id = 1 }).ToSql(); + Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql); + } - [Fact] - public void Where() { - var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql); + [Fact] + public void Where() + { + var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql); - sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM [tb_topic22211] WHERE (id = @id)", sql); + sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM [tb_topic22211] WHERE (id = @id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = delete.Where(item).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = delete.Where(item).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = delete.Where(items).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + sql = delete.Where(items).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM [tb_topic22211] WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - var id = _sqlserverFixture.SqlServer.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteIdentity(); - Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); - } - [Fact] - public void ExecuteDeleted() { + var id = _sqlserverFixture.SqlServer.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteIdentity(); + Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); + } + [Fact] + public void ExecuteDeleted() + { - var item = _sqlserverFixture.SqlServer.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteInserted(); - Assert.Equal(item[0].Id, delete.Where(a => a.Id == item[0].Id).ExecuteDeleted()[0].Id); + var item = _sqlserverFixture.SqlServer.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteInserted(); + Assert.Equal(item[0].Id, delete.Where(a => a.Id == item[0].Id).ExecuteDeleted()[0].Id); - var items = Enumerable.Range(0, 301).Select(a => new Topic { Title = "xxxx" + a, CreateTime = DateTime.Now }); - var itemsInserted = _sqlserverFixture.SqlServer.Insert(items).ExecuteInserted(); - Assert.Equal(items.First().Title, itemsInserted[0].Title); + var items = Enumerable.Range(0, 301).Select(a => new Topic { Title = "xxxx" + a, CreateTime = DateTime.Now }); + var itemsInserted = _sqlserverFixture.SqlServer.Insert(items).ExecuteInserted(); + Assert.Equal(items.First().Title, itemsInserted[0].Title); - Assert.Equal(itemsInserted[0].Id, delete.Where(a => a.Id == itemsInserted[0].Id).ExecuteDeleted()[0].Id); - } + Assert.Equal(itemsInserted[0].Id, delete.Where(a => a.Id == itemsInserted[0].Id).ExecuteDeleted()[0].Id); + } - [Fact] - public void AsTable() { - Assert.Null(_sqlserverFixture.SqlServer.Delete().ToSql()); - var sql = _sqlserverFixture.SqlServer.Delete(new[] { 1, 2 }).AsTable(a => "tb_topic22211AsTable").ToSql(); - Assert.Equal("DELETE FROM [tb_topic22211AsTable] WHERE ([Id] = 1 OR [Id] = 2)", sql); + [Fact] + public void AsTable() + { + Assert.Null(_sqlserverFixture.SqlServer.Delete().ToSql()); + var sql = _sqlserverFixture.SqlServer.Delete(new[] { 1, 2 }).AsTable(a => "tb_topic22211AsTable").ToSql(); + Assert.Equal("DELETE FROM [tb_topic22211AsTable] WHERE ([Id] = 1 OR [Id] = 2)", sql); - sql = _sqlserverFixture.SqlServer.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "tb_topic22211AsTable").ToSql(); - Assert.Equal("DELETE FROM [tb_topic22211AsTable] WHERE ([Id] = 1)", sql); + sql = _sqlserverFixture.SqlServer.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "tb_topic22211AsTable").ToSql(); + Assert.Equal("DELETE FROM [tb_topic22211AsTable] WHERE ([Id] = 1)", sql); - sql = _sqlserverFixture.SqlServer.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "tb_topic22211AsTable").ToSql(); - Assert.Equal("DELETE FROM [tb_topic22211AsTable] WHERE ([Id] = 1 OR [Id] = 2)", sql); + sql = _sqlserverFixture.SqlServer.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "tb_topic22211AsTable").ToSql(); + Assert.Equal("DELETE FROM [tb_topic22211AsTable] WHERE ([Id] = 1 OR [Id] = 2)", sql); - sql = _sqlserverFixture.SqlServer.Delete(new { id = 1 }).AsTable(a => "tb_topic22211AsTable").ToSql(); - Assert.Equal("DELETE FROM [tb_topic22211AsTable] WHERE ([Id] = 1)", sql); - } - } + sql = _sqlserverFixture.SqlServer.Delete(new { id = 1 }).AsTable(a => "tb_topic22211AsTable").ToSql(); + Assert.Equal("DELETE FROM [tb_topic22211AsTable] WHERE ([Id] = 1)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerInsertTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerInsertTest.cs index 3b47f1f1..f1d3748b 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerInsertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerInsertTest.cs @@ -5,134 +5,143 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServer { - [Collection("SqlServerCollection")] - public class SqlServerInsertTest - { - SqlServerFixture _sqlserverFixture; +namespace FreeSql.Tests.SqlServer +{ + [Collection("SqlServerCollection")] + public class SqlServerInsertTest + { + SqlServerFixture _sqlserverFixture; - public SqlServerInsertTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public SqlServerInsertTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - IInsert insert => _sqlserverFixture.SqlServer.Insert(); //�������� + IInsert insert => _sqlserverFixture.SqlServer.Insert(); //�������� - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - - [Fact] - public void AppendData() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - var sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items.First()).ToSql(); - Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title], [CreateTime]) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); + [Fact] + public void AppendData() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items).ToSql(); - Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title], [CreateTime]) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); + var sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items.First()).ToSql(); + Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title], [CreateTime]) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO [tb_topic]([Title]) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items).ToSql(); + Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title], [CreateTime]) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); - sql = insert.IgnoreColumns(a => new { a.CreateTime, a.TypeGuid }).AppendData(items).ToSql(); - Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - } + sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO [tb_topic]([Title]) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - [Fact] - public void InsertColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + sql = insert.IgnoreColumns(a => new { a.CreateTime, a.TypeGuid }).AppendData(items).ToSql(); + Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + } - var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO [tb_topic]([Title]) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + [Fact] + public void InsertColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - sql = insert.AppendData(items).InsertColumns(a =>new { a.Title, a.Clicks }).ToSql(); - Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - } - [Fact] - public void IgnoreColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO [tb_topic]([Title]) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - var sql = insert.AppendData(items).IgnoreColumns(a => new { a.CreateTime, a.TypeGuid }).ToSql(); - Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql(); + Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + } + [Fact] + public void IgnoreColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime, a.TypeGuid }).ToSql(); - Assert.Equal("INSERT INTO [tb_topic]([Clicks]) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); - } - [Fact] - public void ExecuteAffrows() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + var sql = insert.AppendData(items).IgnoreColumns(a => new { a.CreateTime, a.TypeGuid }).ToSql(); + Assert.Equal("INSERT INTO [tb_topic]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime, a.TypeGuid }).ToSql(); + Assert.Equal("INSERT INTO [tb_topic]([Clicks]) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); + } + [Fact] + public void ExecuteAffrows() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - //Assert.Equal(9989, _sqlserverFixture.SqlServer.Insert(items).ExecuteAffrows()); - } - [Fact] - public void ExecuteIdentity() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); - Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); + //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + //Assert.Equal(9989, _sqlserverFixture.SqlServer.Insert(items).ExecuteAffrows()); + } + [Fact] + public void ExecuteIdentity() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + + Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); - //items = Enumerable.Range(0, 9999).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - //var lastId = g.sqlite.Select().Max(a => a.Id); - //Assert.NotEqual(lastId, _sqlserverFixture.SqlServer.Insert(items).ExecuteIdentity()); - } - [Fact] - public void ExecuteInserted() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + //items = Enumerable.Range(0, 9999).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + //var lastId = g.sqlite.Select().Max(a => a.Id); + //Assert.NotEqual(lastId, _sqlserverFixture.SqlServer.Insert(items).ExecuteIdentity()); + } + [Fact] + public void ExecuteInserted() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - var items2 = insert.AppendData(items).ExecuteInserted(); + var items2 = insert.AppendData(items).ExecuteInserted(); - items = Enumerable.Range(0, 90).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - var itemsInserted = _sqlserverFixture.SqlServer.Insert(items).ExecuteInserted(); - Assert.Equal(items.First().Title, itemsInserted.First().Title); - Assert.Equal(items.Last().Title, itemsInserted.Last().Title); - } + items = Enumerable.Range(0, 90).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + var itemsInserted = _sqlserverFixture.SqlServer.Insert(items).ExecuteInserted(); + Assert.Equal(items.First().Title, itemsInserted.First().Title); + Assert.Equal(items.Last().Title, itemsInserted.Last().Title); + } - [Fact] - public void AsTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + [Fact] + public void AsTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - var sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items.First()).AsTable(a => "tb_topicAsTable").ToSql(); - Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title], [CreateTime]) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); + var sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items.First()).AsTable(a => "tb_topicAsTable").ToSql(); + Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title], [CreateTime]) VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); - sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); - Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title], [CreateTime]) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); + sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); + Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title], [CreateTime]) VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); - sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items).InsertColumns(a => a.Title).AsTable(a => "tb_topicAsTable").ToSql(); - Assert.Equal("INSERT INTO [tb_topicAsTable]([Title]) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items).InsertColumns(a => a.Title).AsTable(a => "tb_topicAsTable").ToSql(); + Assert.Equal("INSERT INTO [tb_topicAsTable]([Title]) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = insert.IgnoreColumns(a => new { a.CreateTime, a.TypeGuid }).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); - Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.IgnoreColumns(a => new { a.CreateTime, a.TypeGuid }).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); + Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.IgnoreColumns(a => new { a.Title, a.TypeGuid }).InsertColumns(a => a.Title).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); - Assert.Equal("INSERT INTO [tb_topicAsTable]([Title]) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.IgnoreColumns(a => new { a.Title, a.TypeGuid }).InsertColumns(a => a.Title).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); + Assert.Equal("INSERT INTO [tb_topicAsTable]([Title]) VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "tb_topicAsTable").ToSql(); - Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.IgnoreColumns(a => a.TypeGuid).AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "tb_topicAsTable").ToSql(); + Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.IgnoreColumns(a => new { a.CreateTime, a.TypeGuid }).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); - Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.IgnoreColumns(a => new { a.CreateTime, a.TypeGuid }).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); + Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks], [Title]) VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.IgnoreColumns(a => new { a.CreateTime, a.Title, a.TypeGuid }).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); - Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks]) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); - } - } + sql = insert.IgnoreColumns(a => new { a.CreateTime, a.Title, a.TypeGuid }).AppendData(items).AsTable(a => "tb_topicAsTable").ToSql(); + Assert.Equal("INSERT INTO [tb_topicAsTable]([Clicks]) VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerSelectTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerSelectTest.cs index bdc0325b..09f7855a 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerSelectTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerSelectTest.cs @@ -5,1109 +5,1178 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServer { - [Collection("SqlServerCollection")] - public class SqlServerSelectTest { - - SqlServerFixture _sqlserverFixture; - - public SqlServerSelectTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } - - ISelect select => _sqlserverFixture.SqlServer.Select(); - - [Table(Name = "tb_topic22")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - public partial class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } - - public virtual ICollection Tags { get; set; } - } - public partial class Song_tag { - public int Song_id { get; set; } - public virtual Song Song { get; set; } - - public int Tag_id { get; set; } - public virtual Tag Tag { get; set; } - } - public partial class Tag { - [Column(IsIdentity = true)] - public int Id { get; set; } - public int? Parent_id { get; set; } - public virtual Tag Parent { get; set; } - - public decimal? Ddd { get; set; } - public string Name { get; set; } - - public virtual ICollection Songs { get; set; } - public virtual ICollection Tags { get; set; } - } - - [Fact] - public void AsSelect() { - //OneToOne、ManyToOne - var t0 = _sqlserverFixture.SqlServer.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); - //SELECT a.[Id], a.[Parent_id], a__Parent.[Id] as3, a__Parent.[Parent_id] as4, a__Parent.[Ddd], a__Parent.[Name], a.[Ddd] as7, a.[Name] as8 - //FROM [Tag] a - //LEFT JOIN [Tag] a__Parent ON a__Parent.[Id] = a.[Parent_id] - //LEFT JOIN [Tag] a__Parent__Parent ON a__Parent__Parent.[Id] = a__Parent.[Parent_id] - //WHERE (a__Parent__Parent.[Name] = '粤语') - - //OneToMany - var t1 = _sqlserverFixture.SqlServer.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); - //SELECT a.[Id], a.[Parent_id], a.[Ddd], a.[Name] - //FROM [Tag] a - //WHERE (exists(SELECT 1 - // FROM [Tag] t - // LEFT JOIN [Tag] t__Parent ON t__Parent.[Id] = t.[Parent_id] - // WHERE (t__Parent.[Id] = 10) AND (t.[Parent_id] = a.[Id]) - // limit 0,1)) - - //ManyToMany - var t2 = _sqlserverFixture.SqlServer.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); - //SELECT a.[Id], a.[Create_time], a.[Is_deleted], a.[Title], a.[Url] - //FROM [Song] a - //WHERE(exists(SELECT 1 - // FROM [Song_tag] Mt_Ms - // WHERE(Mt_Ms.[Song_id] = a.[Id]) AND(exists(SELECT 1 - // FROM [Tag] t - // WHERE(t.[Name] = '国语') AND(t.[Id] = Mt_Ms.[Tag_id]) - // limit 0, 1)) - // limit 0, 1)) - } - - [Fact] - public void Lazy() { - var tags = _sqlserverFixture.SqlServer.Select().Where(a => a.Parent.Name == "xxx") - .LeftJoin(a => a.Parent_id == a.Parent.Id) - .ToSql(); - - var songs = _sqlserverFixture.SqlServer.Select().Limit(10).ToList(); - - - } - [Fact] - public void ToDataTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - - Assert.Single(_sqlserverFixture.SqlServer.Insert().AppendData(items.First()).ExecuteInserted()); - Assert.Equal(10, _sqlserverFixture.SqlServer.Insert().AppendData(items).ExecuteInserted().Count); - - //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - //; - //Assert.Equal(9989, _sqlserverFixture.SqlServer.Insert(items).NoneParameter().ExecuteAffrows()); - - var dt1 = select.Limit(10).ToDataTable(); - var dt2 = select.Limit(10).ToDataTable("id, getdate()"); - var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); - } - class TestDto { - public int id { get; set; } - public string name { get; set; } //这是join表的属性 - public int ParentId { get; set; } //这是join表的属性 - } - [Fact] - public void ToList() { - - var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto2 = select.Limit(10).ToList(a => new TestDto()); - var testDto3 = select.Limit(10).ToList(a => new TestDto { }); - var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); - - var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); - var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); - var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); - - _sqlserverFixture.SqlServer.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); - var testGuidId5 = _sqlserverFixture.SqlServer.Select().ToList(); - var testGuidId6 = _sqlserverFixture.SqlServer.Select().ToList(a => a.id); - - var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); - var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); - } - class TestGuidIdToList { - public Guid id { get; set; } - public string title { get; set; } = Guid.NewGuid().ToString(); - } - [Fact] - public void ToOne() { - var testnotfind = select.Where("1=2").First(a => a.CreateTime); - Assert.Equal(default(DateTime), testnotfind); - } - [Fact] - public void ToSql() { - } - [Fact] - public void Any() { - var count = select.Where(a => 1 == 1).Count(); - Assert.False(select.Where(a => 1 == 2).Any()); - Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); - - var sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && - select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - //.Offset(a.Id) - .Any() - ).Any(c => c.Id == a.Id + 10) - ); - var sql2222Tolist = sql2222.ToList(); - - var collectionSelect = select.Where(a => - a.Type.Guid == a.TypeGuid && - a.Type.Parent.Id == a.Type.ParentId && - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) - ); - collectionSelect.ToList(); - } - [Fact] - public void Count() { - var count = select.Where(a => 1 == 1).Count(); - select.Where(a => 1 == 1).Count(out var count2); - Assert.Equal(count, count2); - Assert.Equal(0, select.Where(a => 1 == 2).Count()); - } - [Fact] - public void Master() { - Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); - } - - [Fact] - public void From() { - var query2 = select.From((s, b) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - ); - var sql2 = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid]", sql2); - query2.ToList(); - - var query3 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id) - ); - var sql3 = query3.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid] LEFT JOIN [TestTypeParentInfo] c ON b.[ParentId] = c.[Id]", sql3); - query3.ToList(); - } - [Fact] - public void LeftJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid]", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx' LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid]", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx' LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); - query.ToList(); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId]", sql); - query.ToList(); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] c ON c.[Id] = a__Type.[ParentId]", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid] LEFT JOIN [TestTypeParentInfo] c ON b.[ParentId] = c.[Id]", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); - query.ToList(); - } - [Fact] - public void InnerJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid]", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx' LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid]", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx' LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); - query.ToList(); - - //������� - query = select - .InnerJoin(a => a.Type.Guid == a.TypeGuid) - .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] INNER JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId]", sql); - query.ToList(); - - query = select - .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .InnerJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] INNER JOIN [TestTypeParentInfo] c ON c.[Id] = a__Type.[ParentId]", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .InnerJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid] INNER JOIN [TestTypeParentInfo] c ON b.[ParentId] = c.[Id]", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); - query.ToList(); - - } - [Fact] - public void RightJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid]", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx' LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid]", sql); - query.ToList(); - - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx'", sql); - query.ToList(); - - query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx' LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); - query.ToList(); - - //������� - query = select - .RightJoin(a => a.Type.Guid == a.TypeGuid) - .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] RIGHT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId]", sql); - query.ToList(); - - query = select - .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .RightJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] RIGHT JOIN [TestTypeParentInfo] c ON c.[Id] = a__Type.[ParentId]", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .RightJoin(a => a.TypeGuid == b.Guid) - .RightJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid] RIGHT JOIN [TestTypeParentInfo] c ON b.[ParentId] = c.[Id]", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - query.ToList(); - - query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); - query.ToList(); - - } - [Fact] - public void Where() { - var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); - var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); - var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); - - var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.Where(a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.[Id] = 10)", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE ((a.[Id] = 10 AND a.[Id] > 10 OR a.[Clicks] > 100))", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.[Id] = 10) AND (a.[Clicks] > 100)", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] WHERE (a__Type.[Name] = 'typeTitle')", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] WHERE (a__Type.[Name] = 'typeTitle' AND a__Type.[Guid] = a.[TypeGuid])", sql); - query.ToList(); - - query = select.Where(a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Name] = 'tparent')", sql); - query.ToList(); - - //���û�е������ԣ��򵥶������ - query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b WHERE (b.[Guid] = a.[TypeGuid] AND b.[Name] = 'typeTitle')", sql); - query.ToList(); - - query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b WHERE (b.[Name] = 'typeTitle' AND b.[Guid] = a.[TypeGuid])", sql); - query.ToList(); - - query = select.Where((a, b, c) => c.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeParentInfo] c WHERE (c.[Name] = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .Where(a => a.Id == 10 && c.Name == "xxx") - .Where(a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b, [TestTypeParentInfo] c WHERE (a.[Id] = 10 AND c.[Name] = 'xxx') AND (b.[ParentId] = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.Where("a.clicks > 100 and a.id = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.clicks > 100 and a.id = @id)", sql); - query.ToList(); - } - [Fact] - public void WhereIf() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.WhereIf(true, a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.[Id] = 10)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE ((a.[Id] = 10 AND a.[Id] > 10 OR a.[Clicks] > 100))", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.[Id] = 10) AND (a.[Clicks] > 100)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] WHERE (a__Type.[Name] = 'typeTitle')", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] WHERE (a__Type.[Name] = 'typeTitle' AND a__Type.[Guid] = a.[TypeGuid])", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Name] = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(true, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b, [TestTypeParentInfo] c WHERE (a.[Id] = 10 AND c.[Name] = 'xxx') AND (b.[ParentId] = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(true, "a.clicks > 100 and a.id = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.clicks > 100 and a.id = @id)", sql); - query.ToList(); - - // ==========================================WhereIf(false) - - //����е�������a.Type��a.Type.Parent ���ǵ������� - query = select.WhereIf(false, a => a.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); - query.ToList(); - - query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - query2 = select.From((s, b, c) => s - .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(false, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b, [TestTypeParentInfo] c", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(false, "a.clicks > 100 and a.id = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); - query.ToList(); - } - [Fact] - public void WhereExists() { - var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); - - sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - - //.Offset(a.Id) - - .Any() - ).Any() - ).ToList(); - } - [Fact] - public void GroupBy() { - var groupby = select.From((s, b, c) => s - .Where(a => a.Id == 1) - ) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()) - .Offset(10) - .Limit(2) - .ToList(a => new { - a.Key.tt2, - cou1 = a.Count(), - arg1 = a.Avg(a.Key.mod4), - ccc2 = a.Key.tt2 ?? "now()", - //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") - ccc3 = a.Max(a.Value.Item3.Id) - }); - - var testpid1 = _sqlserverFixture.SqlServer.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); - _sqlserverFixture.SqlServer.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); - - var aggsql1 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist1 = select - .GroupBy(a => a.Title) - .ToList(b => new { - b.Key, - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToSql(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToList(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql3 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum2 = b.Sum(b.Value.TypeGuid), - sum3 = b.Sum(b.Value.Type.Parent.Id) - }); - } - [Fact] - public void ToAggregate() { - var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(Convert.ToInt64(a.Key.Id)), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); - } - [Fact] - public void OrderBy() { - var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); - } - [Fact] - public void Skip_Offset() { - var sql = select.Offset(10).Limit(10).ToList(); - } - [Fact] - public void Take_Limit() { - var sql = select.Limit(10).ToList(); - } - [Fact] - public void Page() { - var sql1 = select.Page(1, 10).ToList(); - var sql2 = select.Page(2, 10).ToList(); - var sql3 = select.Page(3, 10).ToList(); - - var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); - var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); - var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); - } - [Fact] - public void Distinct() { - var t1 = select.Distinct().ToList(a => a.Title); - var t2 = select.Distinct().Limit(10).ToList(a => a.Title); - } - - [Fact] - public void Sum() { - } - [Fact] - public void Min() { - } - [Fact] - public void Max() { - } - [Fact] - public void Avg() { - } - [Fact] - public void As() { - } - - [Fact] - public void AsTable() { - - var listt = select.AsTable((a, b) => "(select * from tb_topic22 where clicks > 10)").Page(1, 10).ToList(); - - Func tableRule = (type, oldname) => { - if (type == typeof(Topic)) return oldname + "AsTable1"; - else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; - return oldname + "AsTable"; - }; - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid]", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx'", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx' LEFT JOIN [TestTypeParentInfoAsTable] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] b ON b.[Guid] = a.[TypeGuid]", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx'", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx' LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfoAsTable] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfoAsTable] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId]", sql); - - query = select - .LeftJoin((a, b) => b.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeInfoAsTable2] b ON b.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfoAsTable] c ON c.[Id] = a__Type.[ParentId]", sql); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] b ON a.[TypeGuid] = b.[Guid] LEFT JOIN [TestTypeParentInfoAsTable] c ON b.[ParentId] = c.[Id]", sql); - - //������϶����㲻�� - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); - - query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); - } - - public class TestInclude_OneToManyModel1 { - [Column(IsIdentity = true)] - public int id { get; set; } - public virtual TestInclude_OneToManyModel2 model2 { get; set; } - - public string m1name { get; set; } - } - public class TestInclude_OneToManyModel2 { - [Column(IsPrimary = true)] - public int model2id { get; set; } - public virtual TestInclude_OneToManyModel1 model1 { get; set; } - - public string m2setting { get; set; } - - public List childs { get; set; } - } - public class TestInclude_OneToManyModel3 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model2111Idaaa { get; set; } - public string title { get; set; } - - public List childs2 { get; set; } - } - public class TestInclude_OneToManyModel4 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model3333Id333 { get; set; } - public string title444 { get; set; } - } - - [Fact] - public void Include_OneToMany() { - var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; - model1.id = (int)_sqlserverFixture.SqlServer.Insert(model1).ExecuteIdentity(); - var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; - _sqlserverFixture.SqlServer.Insert(model2).ExecuteAffrows(); - - var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; - model3_1.id = (int)_sqlserverFixture.SqlServer.Insert(model3_1).ExecuteIdentity(); - var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; - model3_2.id = (int)_sqlserverFixture.SqlServer.Insert(model3_2).ExecuteIdentity(); - var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; - model3_3.id = (int)_sqlserverFixture.SqlServer.Insert(model3_2).ExecuteIdentity(); - - var model4s = new[] { - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } - }; - Assert.Equal(5, _sqlserverFixture.SqlServer.Insert(model4s).ExecuteAffrows()); - - var t0 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t1 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t2 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - - var t00 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t11 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t22 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - } - - public class TestInclude_OneToManyModel11 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2id { get; set; } - public string m3setting { get; set; } - public TestInclude_OneToManyModel22 model2 { get; set; } - public string m1name { get; set; } - } - - public class TestInclude_OneToManyModel22 { - [Column(IsIdentity = true)] - public int id { get; set; } - public string m2setting { get; set; } - public List childs { get; set; } - } - public class TestInclude_OneToManyModel33 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2Id { get; set; } - public string title { get; set; } - public string setting { get; set; } - } - [Fact] - public void Include_OneToMany2() { - string setting = "x"; - var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; - model2.id = (int)_sqlserverFixture.SqlServer.Insert(model2).ExecuteIdentity(); - - var model3s = new[] - { - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} - }; - Assert.Equal(3, _sqlserverFixture.SqlServer.Insert(model3s).ExecuteAffrows()); - - var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; - model1.id = (int)_sqlserverFixture.SqlServer.Insert(model1).ExecuteIdentity(); - - var t1 = _sqlserverFixture.SqlServer.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - - var t11 = _sqlserverFixture.SqlServer.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - } - - [Fact] - public void Include_OneToChilds() { - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_中国" - }; - tag1.Id = (int)_sqlserverFixture.SqlServer.Insert(tag1).ExecuteIdentity(); - var tag1_1 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_北京" - }; - tag1_1.Id = (int)_sqlserverFixture.SqlServer.Insert(tag1_1).ExecuteIdentity(); - var tag1_2 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_上海" - }; - tag1_2.Id = (int)_sqlserverFixture.SqlServer.Insert(tag1_2).ExecuteIdentity(); - - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_美国" - }; - tag2.Id = (int)_sqlserverFixture.SqlServer.Insert(tag2).ExecuteIdentity(); - var tag2_1 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_纽约" - }; - tag2_1.Id = (int)_sqlserverFixture.SqlServer.Insert(tag2_1).ExecuteIdentity(); - var tag2_2 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_华盛顿" - }; - tag2_2.Id = (int)_sqlserverFixture.SqlServer.Insert(tag2_2).ExecuteIdentity(); - - var tags0 = _sqlserverFixture.SqlServer.Select() - .Include(a => a.Parent) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags1 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags2 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags3 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags11 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags22 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags33 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - } - - [Fact] - public void Include_ManyToMany() { - - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_01_中国" - }; - tag1.Id = (int)_sqlserverFixture.SqlServer.Insert(tag1).ExecuteIdentity(); - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_02_美国" - }; - tag2.Id = (int)_sqlserverFixture.SqlServer.Insert(tag2).ExecuteIdentity(); - var tag3 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_03_日本" - }; - tag3.Id = (int)_sqlserverFixture.SqlServer.Insert(tag3).ExecuteIdentity(); - - var song1 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_01_我是中国人.mp3", - Url = "http://ww.baidu.com/" - }; - song1.Id = (int)_sqlserverFixture.SqlServer.Insert(song1).ExecuteIdentity(); - var song2 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_02_爱你一万年.mp3", - Url = "http://ww.163.com/" - }; - song2.Id = (int)_sqlserverFixture.SqlServer.Insert(song2).ExecuteIdentity(); - var song3 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_03_千年等一回.mp3", - Url = "http://ww.sina.com/" - }; - song3.Id = (int)_sqlserverFixture.SqlServer.Insert(song3).ExecuteIdentity(); - - _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); - - var songs1 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs1.Count); - Assert.Equal(2, songs1[0].Tags.Count); - Assert.Equal(1, songs1[1].Tags.Count); - Assert.Equal(3, songs1[2].Tags.Count); - - var songs2 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags, - then => then.IncludeMany(t => t.Songs)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs2.Count); - Assert.Equal(2, songs2[0].Tags.Count); - Assert.Equal(1, songs2[1].Tags.Count); - Assert.Equal(3, songs2[2].Tags.Count); - - var tags3 = _sqlserverFixture.SqlServer.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - - - var songs11 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs11.Count); - Assert.Equal(1, songs11[0].Tags.Count); - Assert.Equal(1, songs11[1].Tags.Count); - Assert.Equal(1, songs11[2].Tags.Count); - - var songs22 = _sqlserverFixture.SqlServer.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.IncludeMany(t => t.Songs.Take(1))) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs22.Count); - Assert.Equal(1, songs22[0].Tags.Count); - Assert.Equal(1, songs22[1].Tags.Count); - Assert.Equal(1, songs22[2].Tags.Count); - - var tags33 = _sqlserverFixture.SqlServer.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs.Take(1)) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - } - } +namespace FreeSql.Tests.SqlServer +{ + [Collection("SqlServerCollection")] + public class SqlServerSelectTest + { + + SqlServerFixture _sqlserverFixture; + + public SqlServerSelectTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } + + ISelect select => _sqlserverFixture.SqlServer.Select(); + + [Table(Name = "tb_topic22")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + public partial class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } + + public virtual ICollection Tags { get; set; } + } + public partial class Song_tag + { + public int Song_id { get; set; } + public virtual Song Song { get; set; } + + public int Tag_id { get; set; } + public virtual Tag Tag { get; set; } + } + public partial class Tag + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public int? Parent_id { get; set; } + public virtual Tag Parent { get; set; } + + public decimal? Ddd { get; set; } + public string Name { get; set; } + + public virtual ICollection Songs { get; set; } + public virtual ICollection Tags { get; set; } + } + + [Fact] + public void AsSelect() + { + //OneToOne、ManyToOne + var t0 = _sqlserverFixture.SqlServer.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); + //SELECT a.[Id], a.[Parent_id], a__Parent.[Id] as3, a__Parent.[Parent_id] as4, a__Parent.[Ddd], a__Parent.[Name], a.[Ddd] as7, a.[Name] as8 + //FROM [Tag] a + //LEFT JOIN [Tag] a__Parent ON a__Parent.[Id] = a.[Parent_id] + //LEFT JOIN [Tag] a__Parent__Parent ON a__Parent__Parent.[Id] = a__Parent.[Parent_id] + //WHERE (a__Parent__Parent.[Name] = '粤语') + + //OneToMany + var t1 = _sqlserverFixture.SqlServer.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); + //SELECT a.[Id], a.[Parent_id], a.[Ddd], a.[Name] + //FROM [Tag] a + //WHERE (exists(SELECT 1 + // FROM [Tag] t + // LEFT JOIN [Tag] t__Parent ON t__Parent.[Id] = t.[Parent_id] + // WHERE (t__Parent.[Id] = 10) AND (t.[Parent_id] = a.[Id]) + // limit 0,1)) + + //ManyToMany + var t2 = _sqlserverFixture.SqlServer.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); + //SELECT a.[Id], a.[Create_time], a.[Is_deleted], a.[Title], a.[Url] + //FROM [Song] a + //WHERE(exists(SELECT 1 + // FROM [Song_tag] Mt_Ms + // WHERE(Mt_Ms.[Song_id] = a.[Id]) AND(exists(SELECT 1 + // FROM [Tag] t + // WHERE(t.[Name] = '国语') AND(t.[Id] = Mt_Ms.[Tag_id]) + // limit 0, 1)) + // limit 0, 1)) + } + + [Fact] + public void Lazy() + { + var tags = _sqlserverFixture.SqlServer.Select().Where(a => a.Parent.Name == "xxx") + .LeftJoin(a => a.Parent_id == a.Parent.Id) + .ToSql(); + + var songs = _sqlserverFixture.SqlServer.Select().Limit(10).ToList(); + + + } + [Fact] + public void ToDataTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + + Assert.Single(_sqlserverFixture.SqlServer.Insert().AppendData(items.First()).ExecuteInserted()); + Assert.Equal(10, _sqlserverFixture.SqlServer.Insert().AppendData(items).ExecuteInserted().Count); + + //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + //; + //Assert.Equal(9989, _sqlserverFixture.SqlServer.Insert(items).NoneParameter().ExecuteAffrows()); + + var dt1 = select.Limit(10).ToDataTable(); + var dt2 = select.Limit(10).ToDataTable("id, getdate()"); + var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); + } + class TestDto + { + public int id { get; set; } + public string name { get; set; } //这是join表的属性 + public int ParentId { get; set; } //这是join表的属性 + } + [Fact] + public void ToList() + { + + var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto2 = select.Limit(10).ToList(a => new TestDto()); + var testDto3 = select.Limit(10).ToList(a => new TestDto { }); + var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); + + var testDto11 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto22 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); + var testDto33 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); + var testDto44 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); + + _sqlserverFixture.SqlServer.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); + var testGuidId5 = _sqlserverFixture.SqlServer.Select().ToList(); + var testGuidId6 = _sqlserverFixture.SqlServer.Select().ToList(a => a.id); + + var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); + var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); + } + class TestGuidIdToList + { + public Guid id { get; set; } + public string title { get; set; } = Guid.NewGuid().ToString(); + } + [Fact] + public void ToOne() + { + var testnotfind = select.Where("1=2").First(a => a.CreateTime); + Assert.Equal(default(DateTime), testnotfind); + } + [Fact] + public void ToSql() + { + } + [Fact] + public void Any() + { + var count = select.Where(a => 1 == 1).Count(); + Assert.False(select.Where(a => 1 == 2).Any()); + Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); + + var sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && + select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + //.Offset(a.Id) + .Any() + ).Any(c => c.Id == a.Id + 10) + ); + var sql2222Tolist = sql2222.ToList(); + + var collectionSelect = select.Where(a => + a.Type.Guid == a.TypeGuid && + a.Type.Parent.Id == a.Type.ParentId && + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) + ); + collectionSelect.ToList(); + } + [Fact] + public void Count() + { + var count = select.Where(a => 1 == 1).Count(); + select.Where(a => 1 == 1).Count(out var count2); + Assert.Equal(count, count2); + Assert.Equal(0, select.Where(a => 1 == 2).Count()); + } + [Fact] + public void Master() + { + Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); + } + + [Fact] + public void From() + { + var query2 = select.From((s, b) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + ); + var sql2 = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid]", sql2); + query2.ToList(); + + var query3 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id) + ); + var sql3 = query3.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid] LEFT JOIN [TestTypeParentInfo] c ON b.[ParentId] = c.[Id]", sql3); + query3.ToList(); + } + [Fact] + public void LeftJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid]", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx' LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid]", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx' LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); + query.ToList(); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId]", sql); + query.ToList(); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] c ON c.[Id] = a__Type.[ParentId]", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid] LEFT JOIN [TestTypeParentInfo] c ON b.[ParentId] = c.[Id]", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); + query.ToList(); + } + [Fact] + public void InnerJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid]", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx' LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid]", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx' LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); + query.ToList(); + + //������� + query = select + .InnerJoin(a => a.Type.Guid == a.TypeGuid) + .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] INNER JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId]", sql); + query.ToList(); + + query = select + .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .InnerJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] INNER JOIN [TestTypeParentInfo] c ON c.[Id] = a__Type.[ParentId]", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .InnerJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid] INNER JOIN [TestTypeParentInfo] c ON b.[ParentId] = c.[Id]", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.InnerJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a INNER JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); + query.ToList(); + + } + [Fact] + public void RightJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.RightJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid]", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx' LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid]", sql); + query.ToList(); + + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx'", sql); + query.ToList(); + + query = select.RightJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx' LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); + query.ToList(); + + //������� + query = select + .RightJoin(a => a.Type.Guid == a.TypeGuid) + .RightJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] RIGHT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId]", sql); + query.ToList(); + + query = select + .RightJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .RightJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] RIGHT JOIN [TestTypeParentInfo] c ON c.[Id] = a__Type.[ParentId]", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .RightJoin(a => a.TypeGuid == b.Guid) + .RightJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN [TestTypeInfo] b ON a.[TypeGuid] = b.[Guid] RIGHT JOIN [TestTypeParentInfo] c ON b.[ParentId] = c.[Id]", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + query.ToList(); + + query = select.RightJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a RIGHT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); + query.ToList(); + + } + [Fact] + public void Where() + { + var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); + var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); + var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); + + var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.Where(a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.[Id] = 10)", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE ((a.[Id] = 10 AND a.[Id] > 10 OR a.[Clicks] > 100))", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.[Id] = 10) AND (a.[Clicks] > 100)", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] WHERE (a__Type.[Name] = 'typeTitle')", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] WHERE (a__Type.[Name] = 'typeTitle' AND a__Type.[Guid] = a.[TypeGuid])", sql); + query.ToList(); + + query = select.Where(a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Name] = 'tparent')", sql); + query.ToList(); + + //���û�е������ԣ��򵥶������ + query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b WHERE (b.[Guid] = a.[TypeGuid] AND b.[Name] = 'typeTitle')", sql); + query.ToList(); + + query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b WHERE (b.[Name] = 'typeTitle' AND b.[Guid] = a.[TypeGuid])", sql); + query.ToList(); + + query = select.Where((a, b, c) => c.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeParentInfo] c WHERE (c.[Name] = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .Where(a => a.Id == 10 && c.Name == "xxx") + .Where(a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b, [TestTypeParentInfo] c WHERE (a.[Id] = 10 AND c.[Name] = 'xxx') AND (b.[ParentId] = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.Where("a.clicks > 100 and a.id = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.clicks > 100 and a.id = @id)", sql); + query.ToList(); + } + [Fact] + public void WhereIf() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.WhereIf(true, a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.[Id] = 10)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE ((a.[Id] = 10 AND a.[Id] > 10 OR a.[Clicks] > 100))", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.[Id] = 10) AND (a.[Clicks] > 100)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] WHERE (a__Type.[Name] = 'typeTitle')", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] WHERE (a__Type.[Name] = 'typeTitle' AND a__Type.[Guid] = a.[TypeGuid])", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22] a LEFT JOIN [TestTypeInfo] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfo] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Name] = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(true, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b, [TestTypeParentInfo] c WHERE (a.[Id] = 10 AND c.[Name] = 'xxx') AND (b.[ParentId] = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(true, "a.clicks > 100 and a.id = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a WHERE (a.clicks > 100 and a.id = @id)", sql); + query.ToList(); + + // ==========================================WhereIf(false) + + //����е�������a.Type��a.Type.Parent ���ǵ������� + query = select.WhereIf(false, a => a.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); + query.ToList(); + + query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + query2 = select.From((s, b, c) => s + .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(false, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a, [TestTypeInfo] b, [TestTypeParentInfo] c", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(false, "a.clicks > 100 and a.id = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22] a", sql); + query.ToList(); + } + [Fact] + public void WhereExists() + { + var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); + + sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + + //.Offset(a.Id) + + .Any() + ).Any() + ).ToList(); + } + [Fact] + public void GroupBy() + { + var groupby = select.From((s, b, c) => s + .Where(a => a.Id == 1) + ) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()) + .Offset(10) + .Limit(2) + .ToList(a => new + { + a.Key.tt2, + cou1 = a.Count(), + arg1 = a.Avg(a.Key.mod4), + ccc2 = a.Key.tt2 ?? "now()", + //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") + ccc3 = a.Max(a.Value.Item3.Id) + }); + + var testpid1 = _sqlserverFixture.SqlServer.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); + _sqlserverFixture.SqlServer.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); + + var aggsql1 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist1 = select + .GroupBy(a => a.Title) + .ToList(b => new + { + b.Key, + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToSql(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToList(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql3 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum2 = b.Sum(b.Value.TypeGuid), + sum3 = b.Sum(b.Value.Type.Parent.Id) + }); + } + [Fact] + public void ToAggregate() + { + var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(Convert.ToInt64(a.Key.Id)), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); + } + [Fact] + public void OrderBy() + { + var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); + } + [Fact] + public void Skip_Offset() + { + var sql = select.Offset(10).Limit(10).ToList(); + } + [Fact] + public void Take_Limit() + { + var sql = select.Limit(10).ToList(); + } + [Fact] + public void Page() + { + var sql1 = select.Page(1, 10).ToList(); + var sql2 = select.Page(2, 10).ToList(); + var sql3 = select.Page(3, 10).ToList(); + + var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); + var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); + var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); + } + [Fact] + public void Distinct() + { + var t1 = select.Distinct().ToList(a => a.Title); + var t2 = select.Distinct().Limit(10).ToList(a => a.Title); + } + + [Fact] + public void Sum() + { + } + [Fact] + public void Min() + { + } + [Fact] + public void Max() + { + } + [Fact] + public void Avg() + { + } + [Fact] + public void As() + { + } + + [Fact] + public void AsTable() + { + + var listt = select.AsTable((a, b) => "(select * from tb_topic22 where clicks > 10)").Page(1, 10).ToList(); + + Func tableRule = (type, oldname) => + { + if (type == typeof(Topic)) return oldname + "AsTable1"; + else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; + return oldname + "AsTable"; + }; + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid]", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx'", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] AND a__Type.[Name] = 'xxx' LEFT JOIN [TestTypeParentInfoAsTable] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] b ON b.[Guid] = a.[TypeGuid]", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx'", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] b ON b.[Guid] = a.[TypeGuid] AND b.[Name] = 'xxx' LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfoAsTable] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId] WHERE (a__Type__Parent.[Id] = 10)", sql); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a__Type.[Guid], a__Type.[ParentId], a__Type.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfoAsTable] a__Type__Parent ON a__Type__Parent.[Id] = a__Type.[ParentId]", sql); + + query = select + .LeftJoin((a, b) => b.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] a__Type ON a__Type.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeInfoAsTable2] b ON b.[Guid] = a.[TypeGuid] LEFT JOIN [TestTypeParentInfoAsTable] c ON c.[Id] = a__Type.[ParentId]", sql); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], b.[Guid], b.[ParentId], b.[Name], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN [TestTypeInfoAsTable2] b ON a.[TypeGuid] = b.[Guid] LEFT JOIN [TestTypeParentInfoAsTable] c ON b.[ParentId] = c.[Id]", sql); + + //������϶����㲻�� + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid", sql); + + query = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", new { bname = "xxx" }).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.[Id], a.[Clicks], a.[TypeGuid], a.[Title], a.[CreateTime] FROM [tb_topic22AsTable1] a LEFT JOIN TestTypeInfo b on b.Guid = a.TypeGuid and b.Name = @bname", sql); + } + + public class TestInclude_OneToManyModel1 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public virtual TestInclude_OneToManyModel2 model2 { get; set; } + + public string m1name { get; set; } + } + public class TestInclude_OneToManyModel2 + { + [Column(IsPrimary = true)] + public int model2id { get; set; } + public virtual TestInclude_OneToManyModel1 model1 { get; set; } + + public string m2setting { get; set; } + + public List childs { get; set; } + } + public class TestInclude_OneToManyModel3 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model2111Idaaa { get; set; } + public string title { get; set; } + + public List childs2 { get; set; } + } + public class TestInclude_OneToManyModel4 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model3333Id333 { get; set; } + public string title444 { get; set; } + } + + [Fact] + public void Include_OneToMany() + { + var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; + model1.id = (int)_sqlserverFixture.SqlServer.Insert(model1).ExecuteIdentity(); + var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; + _sqlserverFixture.SqlServer.Insert(model2).ExecuteAffrows(); + + var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; + model3_1.id = (int)_sqlserverFixture.SqlServer.Insert(model3_1).ExecuteIdentity(); + var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; + model3_2.id = (int)_sqlserverFixture.SqlServer.Insert(model3_2).ExecuteIdentity(); + var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; + model3_3.id = (int)_sqlserverFixture.SqlServer.Insert(model3_2).ExecuteIdentity(); + + var model4s = new[] { + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } + }; + Assert.Equal(5, _sqlserverFixture.SqlServer.Insert(model4s).ExecuteAffrows()); + + var t0 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t1 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t2 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + + var t00 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t11 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t22 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + } + + public class TestInclude_OneToManyModel11 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2id { get; set; } + public string m3setting { get; set; } + public TestInclude_OneToManyModel22 model2 { get; set; } + public string m1name { get; set; } + } + + public class TestInclude_OneToManyModel22 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public string m2setting { get; set; } + public List childs { get; set; } + } + public class TestInclude_OneToManyModel33 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2Id { get; set; } + public string title { get; set; } + public string setting { get; set; } + } + [Fact] + public void Include_OneToMany2() + { + string setting = "x"; + var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; + model2.id = (int)_sqlserverFixture.SqlServer.Insert(model2).ExecuteIdentity(); + + var model3s = new[] + { + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} + }; + Assert.Equal(3, _sqlserverFixture.SqlServer.Insert(model3s).ExecuteAffrows()); + + var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; + model1.id = (int)_sqlserverFixture.SqlServer.Insert(model1).ExecuteIdentity(); + + var t1 = _sqlserverFixture.SqlServer.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + + var t11 = _sqlserverFixture.SqlServer.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + } + + [Fact] + public void Include_OneToChilds() + { + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_中国" + }; + tag1.Id = (int)_sqlserverFixture.SqlServer.Insert(tag1).ExecuteIdentity(); + var tag1_1 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_北京" + }; + tag1_1.Id = (int)_sqlserverFixture.SqlServer.Insert(tag1_1).ExecuteIdentity(); + var tag1_2 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_上海" + }; + tag1_2.Id = (int)_sqlserverFixture.SqlServer.Insert(tag1_2).ExecuteIdentity(); + + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_美国" + }; + tag2.Id = (int)_sqlserverFixture.SqlServer.Insert(tag2).ExecuteIdentity(); + var tag2_1 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_纽约" + }; + tag2_1.Id = (int)_sqlserverFixture.SqlServer.Insert(tag2_1).ExecuteIdentity(); + var tag2_2 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_华盛顿" + }; + tag2_2.Id = (int)_sqlserverFixture.SqlServer.Insert(tag2_2).ExecuteIdentity(); + + var tags0 = _sqlserverFixture.SqlServer.Select() + .Include(a => a.Parent) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags1 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags2 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags3 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags11 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags22 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags33 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + } + + [Fact] + public void Include_ManyToMany() + { + + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_01_中国" + }; + tag1.Id = (int)_sqlserverFixture.SqlServer.Insert(tag1).ExecuteIdentity(); + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_02_美国" + }; + tag2.Id = (int)_sqlserverFixture.SqlServer.Insert(tag2).ExecuteIdentity(); + var tag3 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_03_日本" + }; + tag3.Id = (int)_sqlserverFixture.SqlServer.Insert(tag3).ExecuteIdentity(); + + var song1 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_01_我是中国人.mp3", + Url = "http://ww.baidu.com/" + }; + song1.Id = (int)_sqlserverFixture.SqlServer.Insert(song1).ExecuteIdentity(); + var song2 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_02_爱你一万年.mp3", + Url = "http://ww.163.com/" + }; + song2.Id = (int)_sqlserverFixture.SqlServer.Insert(song2).ExecuteIdentity(); + var song3 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_03_千年等一回.mp3", + Url = "http://ww.sina.com/" + }; + song3.Id = (int)_sqlserverFixture.SqlServer.Insert(song3).ExecuteIdentity(); + + _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + _sqlserverFixture.SqlServer.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); + + var songs1 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs1.Count); + Assert.Equal(2, songs1[0].Tags.Count); + Assert.Equal(1, songs1[1].Tags.Count); + Assert.Equal(3, songs1[2].Tags.Count); + + var songs2 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags, + then => then.IncludeMany(t => t.Songs)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs2.Count); + Assert.Equal(2, songs2[0].Tags.Count); + Assert.Equal(1, songs2[1].Tags.Count); + Assert.Equal(3, songs2[2].Tags.Count); + + var tags3 = _sqlserverFixture.SqlServer.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + + + var songs11 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs11.Count); + Assert.Equal(1, songs11[0].Tags.Count); + Assert.Equal(1, songs11[1].Tags.Count); + Assert.Equal(1, songs11[2].Tags.Count); + + var songs22 = _sqlserverFixture.SqlServer.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.IncludeMany(t => t.Songs.Take(1))) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs22.Count); + Assert.Equal(1, songs22[0].Tags.Count); + Assert.Equal(1, songs22[1].Tags.Count); + Assert.Equal(1, songs22[2].Tags.Count); + + var tags33 = _sqlserverFixture.SqlServer.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs.Take(1)) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerUpdateTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerUpdateTest.cs index 7522065d..cac3f57b 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerUpdateTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/Curd/SqlServerUpdateTest.cs @@ -4,135 +4,149 @@ using System; using System.Collections.Generic; using Xunit; -namespace FreeSql.Tests.SqlServer { - [Collection("SqlServerCollection")] - public class SqlServerUpdateTest { +namespace FreeSql.Tests.SqlServer +{ + [Collection("SqlServerCollection")] + public class SqlServerUpdateTest + { - SqlServerFixture _sqlserverFixture; + SqlServerFixture _sqlserverFixture; - public SqlServerUpdateTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public SqlServerUpdateTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - IUpdate update => _sqlserverFixture.SqlServer.Update(); + IUpdate update => _sqlserverFixture.SqlServer.Update(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - - [Fact] - public void Dywhere() { - Assert.Null(_sqlserverFixture.SqlServer.Update().ToSql()); - Assert.Equal("UPDATE [tb_topic] SET title='test' \r\nWHERE ([Id] = 1 OR [Id] = 2)", _sqlserverFixture.SqlServer.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); - Assert.Equal("UPDATE [tb_topic] SET title='test1' \r\nWHERE ([Id] = 1)", _sqlserverFixture.SqlServer.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE [tb_topic] SET title='test1' \r\nWHERE ([Id] = 1 OR [Id] = 2)", _sqlserverFixture.SqlServer.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE [tb_topic] SET title='test1' \r\nWHERE ([Id] = 1)", _sqlserverFixture.SqlServer.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); - } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void SetSource() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => a.TypeGuid).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Clicks] = @p_0, [Title] = @p_1, [CreateTime] = @p_2 WHERE ([Id] = 1)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(_sqlserverFixture.SqlServer.Update().ToSql()); + Assert.Equal("UPDATE [tb_topic] SET title='test' \r\nWHERE ([Id] = 1 OR [Id] = 2)", _sqlserverFixture.SqlServer.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); + Assert.Equal("UPDATE [tb_topic] SET title='test1' \r\nWHERE ([Id] = 1)", _sqlserverFixture.SqlServer.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE [tb_topic] SET title='test1' \r\nWHERE ([Id] = 1 OR [Id] = 2)", _sqlserverFixture.SqlServer.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE [tb_topic] SET title='test1' \r\nWHERE ([Id] = 1)", _sqlserverFixture.SqlServer.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); + } - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + [Fact] + public void SetSource() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => a.TypeGuid).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Clicks] = @p_0, [Title] = @p_1, [CreateTime] = @p_2 WHERE ([Id] = 1)", sql); - sql = update.SetSource(items).IgnoreColumns(a => a.TypeGuid).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Clicks] = CASE [Id] WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, [Title] = CASE [Id] WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, [CreateTime] = CASE [Id] WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime, a.TypeGuid }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Title] = CASE [Id] WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).IgnoreColumns(a => a.TypeGuid).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Clicks] = CASE [Id] WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, [Title] = CASE [Id] WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, [CreateTime] = CASE [Id] WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).IgnoreColumns(a => a.TypeGuid).Set(a => a.CreateTime, new DateTime(2020,1,1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [CreateTime] = @p_0 WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void IgnoreColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime, a.TypeGuid }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Title] = @p_0 WHERE ([Id] = 1)", sql); - } - [Fact] - public void UpdateColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Title] = @p_0 WHERE ([Id] = 1)", sql); - } - [Fact] - public void Set() { - var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Title] = @p_0 WHERE ([Id] = 1)", sql); + sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime, a.TypeGuid }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Title] = CASE [Id] WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Title] = @p_0, [CreateTime] = @p_1 WHERE ([Id] = 1)", sql); + sql = update.SetSource(items).IgnoreColumns(a => a.TypeGuid).Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [CreateTime] = @p_0 WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void IgnoreColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime, a.TypeGuid }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Title] = @p_0 WHERE ([Id] = 1)", sql); + } + [Fact] + public void UpdateColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Title] = @p_0 WHERE ([Id] = 1)", sql); + } + [Fact] + public void Set() + { + var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Title] = @p_0 WHERE ([Id] = 1)", sql); - sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Clicks] = isnull([Clicks], 0) * 10 / 1 WHERE ([Id] = 1)", sql); + sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Title] = @p_0, [CreateTime] = @p_1 WHERE ([Id] = 1)", sql); - sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Id] = ([Id] - 10) WHERE ([Id] = 1)", sql); + sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Clicks] = isnull([Clicks], 0) * 10 / 1 WHERE ([Id] = 1)", sql); - int incrv = 10; - sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Clicks] = isnull([Clicks], 0) * 10 / 1 WHERE ([Id] = 1)", sql); + sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Id] = ([Id] - 10) WHERE ([Id] = 1)", sql); - sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Id] = ([Id] - 10) WHERE ([Id] = 1)", sql); + int incrv = 10; + sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Clicks] = isnull([Clicks], 0) * 10 / 1 WHERE ([Id] = 1)", sql); - sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Clicks] = [Clicks] * 10 / 1 WHERE ([Id] = 1)", sql); + sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Id] = ([Id] - 10) WHERE ([Id] = 1)", sql); - sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET [Id] = 10 WHERE ([Id] = 1)", sql); - } - [Fact] - public void SetRaw() { - var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + @incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET clicks = clicks + @incrClick WHERE ([Id] = 1)", sql); - } - [Fact] - public void Where() { - var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET title='newtitle' WHERE ([Id] = 1)", sql); + sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Clicks] = [Clicks] * 10 / 1 WHERE ([Id] = 1)", sql); - sql = update.Where("id = @id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET title='newtitle' WHERE (id = @id)", sql); + sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET [Id] = 10 WHERE ([Id] = 1)", sql); + } + [Fact] + public void SetRaw() + { + var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + @incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET clicks = clicks + @incrClick WHERE ([Id] = 1)", sql); + } + [Fact] + public void Where() + { + var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET title='newtitle' WHERE ([Id] = 1)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET title='newtitle' WHERE ([Id] = 1)", sql); + sql = update.Where("id = @id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET title='newtitle' WHERE (id = @id)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE [tb_topic] SET title='newtitle' WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET title='newtitle' WHERE ([Id] = 1)", sql); - } - [Fact] - public void ExecuteAffrows() { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE [tb_topic] SET title='newtitle' WHERE ([Id] IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteUpdated() { + } + [Fact] + public void ExecuteAffrows() + { - } + } + [Fact] + public void ExecuteUpdated() + { - [Fact] - public void AsTable() { - Assert.Null(_sqlserverFixture.SqlServer.Update().ToSql()); - Assert.Equal("UPDATE [tb_topicAsTable] SET title='test' \r\nWHERE ([Id] = 1 OR [Id] = 2)", _sqlserverFixture.SqlServer.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE [tb_topicAsTable] SET title='test1' \r\nWHERE ([Id] = 1)", _sqlserverFixture.SqlServer.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE [tb_topicAsTable] SET title='test1' \r\nWHERE ([Id] = 1 OR [Id] = 2)", _sqlserverFixture.SqlServer.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE [tb_topicAsTable] SET title='test1' \r\nWHERE ([Id] = 1)", _sqlserverFixture.SqlServer.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - } - } + } + + [Fact] + public void AsTable() + { + Assert.Null(_sqlserverFixture.SqlServer.Update().ToSql()); + Assert.Equal("UPDATE [tb_topicAsTable] SET title='test' \r\nWHERE ([Id] = 1 OR [Id] = 2)", _sqlserverFixture.SqlServer.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE [tb_topicAsTable] SET title='test1' \r\nWHERE ([Id] = 1)", _sqlserverFixture.SqlServer.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE [tb_topicAsTable] SET title='test1' \r\nWHERE ([Id] = 1 OR [Id] = 2)", _sqlserverFixture.SqlServer.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE [tb_topicAsTable] SET title='test1' \r\nWHERE ([Id] = 1)", _sqlserverFixture.SqlServer.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/BoolNullableTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/BoolNullableTest.cs index fb573c7b..aa6468a1 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/BoolNullableTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/BoolNullableTest.cs @@ -3,1569 +3,1604 @@ using FreeSql.Tests.DataContext.SqlServer; using System; using Xunit; -namespace FreeSql.Tests.SqlServerMapType { - [Collection("SqlServerCollection")] - public class BoolNullableTest { - - SqlServerFixture _sqlserverFixture; - - public BoolNullableTest(SqlServerFixture sqlserverFixture) { - _sqlserverFixture = sqlserverFixture; - } - - class BoolNullableMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool))] - public bool? tobool { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool? tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool? tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool? toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool? toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool? toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool? tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool? tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool? tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool? tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool? tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool? toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool? toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool? touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool? touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool? toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool? toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool? tostring { get; set; } = true; - } - [Fact] - public void Bool() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item = new BoolNullableMap { tobool = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item = new BoolNullableMap { tobool = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update all - item.tobool = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item.tobool = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item.tobool = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item = new BoolNullableMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item = new BoolNullableMap { tosbyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item.tosbyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item.tosbytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item = new BoolNullableMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item = new BoolNullableMap { toshort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item.toshort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item.toshortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item = new BoolNullableMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item = new BoolNullableMap { toint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item.toint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item = new BoolNullableMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item = new BoolNullableMap { tointnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item.tointnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item = new BoolNullableMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item = new BoolNullableMap { tolong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item.tolong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item.tolongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item = new BoolNullableMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item = new BoolNullableMap { tobyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item.tobyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item.tobytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item = new BoolNullableMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item = new BoolNullableMap { toushort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item.toushort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item.toushortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item = new BoolNullableMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item = new BoolNullableMap { touint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item.touint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item = new BoolNullableMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item = new BoolNullableMap { touintnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item.touintnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item = new BoolNullableMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item = new BoolNullableMap { toulong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item.toulong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item.toulongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item = new BoolNullableMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item = new BoolNullableMap { tostring = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item.tostring = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.SqlServerMapType +{ + [Collection("SqlServerCollection")] + public class BoolNullableTest + { + + SqlServerFixture _sqlserverFixture; + + public BoolNullableTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } + + class BoolNullableMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool))] + public bool? tobool { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool? tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool? tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool? toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool? toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool? toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool? tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool? tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool? tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool? tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool? tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool? toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool? toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool? touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool? touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool? toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool? toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool? tostring { get; set; } = true; + } + [Fact] + public void Bool() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item = new BoolNullableMap { tobool = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item = new BoolNullableMap { tobool = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update all + item.tobool = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item.tobool = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item.tobool = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item = new BoolNullableMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item = new BoolNullableMap { tosbyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item.tosbyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item.tosbytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item = new BoolNullableMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item = new BoolNullableMap { toshort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item.toshort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item.toshortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item = new BoolNullableMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item = new BoolNullableMap { toint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item.toint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item = new BoolNullableMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item = new BoolNullableMap { tointnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item.tointnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item = new BoolNullableMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item = new BoolNullableMap { tolong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item.tolong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item.tolongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item = new BoolNullableMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item = new BoolNullableMap { tobyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item.tobyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item.tobytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item = new BoolNullableMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item = new BoolNullableMap { toushort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item.toushort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item.toushortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item = new BoolNullableMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item = new BoolNullableMap { touint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item.touint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item = new BoolNullableMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item = new BoolNullableMap { touintnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item.touintnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item = new BoolNullableMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item = new BoolNullableMap { toulong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item.toulong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item.toulongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item = new BoolNullableMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item = new BoolNullableMap { tostring = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item.tostring = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/BoolTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/BoolTest.cs index 99d60295..dd843638 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/BoolTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/BoolTest.cs @@ -3,1102 +3,1137 @@ using FreeSql.Tests.DataContext.SqlServer; using System; using Xunit; -namespace FreeSql.Tests.SqlServerMapType { - [Collection("SqlServerCollection")] - public class BoolTest { - - SqlServerFixture _sqlserverFixture; - - public BoolTest(SqlServerFixture sqlserverFixture) { - _sqlserverFixture = sqlserverFixture; - } - - class BoolMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool?))] - public bool toboolnullable { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool tostring { get; set; } = true; - } - - [Fact] - public void BoolNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item = new BoolMap { toboolnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update all - item.toboolnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item.toboolnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toboolnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toboolnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item = new BoolMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item = new BoolMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item = new BoolMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item = new BoolMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item = new BoolMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item = new BoolMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item = new BoolMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item = new BoolMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item = new BoolMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item = new BoolMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item = new BoolMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item = new BoolMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item = new BoolMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item = new BoolMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item = new BoolMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item = new BoolMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item = new BoolMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.SqlServerMapType +{ + [Collection("SqlServerCollection")] + public class BoolTest + { + + SqlServerFixture _sqlserverFixture; + + public BoolTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } + + class BoolMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool?))] + public bool toboolnullable { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool tostring { get; set; } = true; + } + + [Fact] + public void BoolNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item = new BoolMap { toboolnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update all + item.toboolnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item.toboolnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toboolnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toboolnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item = new BoolMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item = new BoolMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item = new BoolMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item = new BoolMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item = new BoolMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item = new BoolMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item = new BoolMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item = new BoolMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item = new BoolMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item = new BoolMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item = new BoolMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item = new BoolMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item = new BoolMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item = new BoolMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item = new BoolMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item = new BoolMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item = new BoolMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/EnumTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/EnumTest.cs index f7fc4950..49e629b6 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/EnumTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/EnumTest.cs @@ -4,260 +4,268 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.SqlServerMapType { - [Collection("SqlServerCollection")] - public class EnumTest { +namespace FreeSql.Tests.SqlServerMapType +{ + [Collection("SqlServerCollection")] + public class EnumTest + { - SqlServerFixture _sqlserverFixture; + SqlServerFixture _sqlserverFixture; - public EnumTest(SqlServerFixture sqlserverFixture) { - _sqlserverFixture = sqlserverFixture; - } + public EnumTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - class EnumTestMap { - public Guid id { get; set; } + class EnumTestMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(int))] - public ToStringMapEnum enum_to_int { get; set; } - [Column(MapType = typeof(int?))] - public ToStringMapEnum? enumnullable_to_int { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void EnumToString() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(int))] + public ToStringMapEnum enum_to_int { get; set; } + [Column(MapType = typeof(int?))] + public ToStringMapEnum? enumnullable_to_int { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void EnumToString() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToString() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToString() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void EnumToInt() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + [Fact] + public void EnumToInt() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //update all - item.enum_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update all + item.enum_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - item.enum_to_int = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + item.enum_to_int = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToInt() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToInt() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); + item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); - //update all - item.enumnullable_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); + //update all + item.enumnullable_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); - item.enumnullable_to_int = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + item.enumnullable_to_int = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/ToStringTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/ToStringTest.cs index 5fec98c7..1d5a1c3c 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/ToStringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/MapType/ToStringTest.cs @@ -4,562 +4,576 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.SqlServerMapType { - [Collection("SqlServerCollection")] - public class ToStringTest { - SqlServerFixture _sqlserverFixture; +namespace FreeSql.Tests.SqlServerMapType +{ + [Collection("SqlServerCollection")] + public class ToStringTest + { + SqlServerFixture _sqlserverFixture; - public ToStringTest(SqlServerFixture sqlserverFixture) { - _sqlserverFixture = sqlserverFixture; - } + public ToStringTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - class ToStringMap { - public Guid id { get; set; } + class ToStringMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan timespan_to_string { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan? timespannullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan timespan_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan? timespannullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime datetime_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime? datetimenullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime datetime_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime? datetimenullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid guid_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid? guidnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid guid_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid? guidnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger biginteger_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger? bigintegernullable_to_string { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void Enum1() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(string))] + public BigInteger biginteger_to_string { get; set; } + [Column(MapType = typeof(string))] + public BigInteger? bigintegernullable_to_string { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void Enum1() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigInteger1() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(0, find.biginteger_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigInteger1() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(0, find.biginteger_to_string); - item = new ToStringMap { biginteger_to_string = 100 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(100, find.biginteger_to_string); + item = new ToStringMap { biginteger_to_string = 100 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(100, find.biginteger_to_string); - //update all - item.biginteger_to_string = 200; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(200, find.biginteger_to_string); + //update all + item.biginteger_to_string = 200; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(200, find.biginteger_to_string); - item.biginteger_to_string = 205; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(205, find.biginteger_to_string); + item.biginteger_to_string = 205; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(205, find.biginteger_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(522, find.biginteger_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(522, find.biginteger_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(10005, find.biginteger_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(10005, find.biginteger_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigIntegerNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigIntegerNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - item = new ToStringMap { bigintegernullable_to_string = 101 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(101, find.bigintegernullable_to_string); + item = new ToStringMap { bigintegernullable_to_string = 101 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(101, find.bigintegernullable_to_string); - //update all - item.bigintegernullable_to_string = 2004; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(2004, find.bigintegernullable_to_string); + //update all + item.bigintegernullable_to_string = 2004; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(2004, find.bigintegernullable_to_string); - item.bigintegernullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + item.bigintegernullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(998, find.bigintegernullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(998, find.bigintegernullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.bigintegernullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.bigintegernullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpan1() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.Zero, find.timespan_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpan1() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.Zero, find.timespan_to_string); - item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); + item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); - //update all - item.timespan_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); + //update all + item.timespan_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpanNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpanNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); + item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); - //update all - item.timespannullable_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); + //update all + item.timespannullable_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); - item.timespannullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + item.timespannullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.timespannullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.timespannullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTime1() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.MinValue, find.datetime_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTime1() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.MinValue, find.datetime_to_string); - item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); + item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); - //update all - item.datetime_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); + //update all + item.datetime_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTimeNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTimeNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); + item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); - //update all - item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); + //update all + item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); - item.datetimenullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + item.datetimenullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.datetimenullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.datetimenullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void Guid1() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(Guid.Empty, find.guid_to_string); + [Fact] + public void Guid1() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(Guid.Empty, find.guid_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guid_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guid_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update all - newid = Guid.NewGuid(); - item.guid_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + //update all + newid = Guid.NewGuid(); + item.guid_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guid_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guid_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void GuidNullable() { - //insert - var orm = _sqlserverFixture.SqlServer; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void GuidNullable() + { + //insert + var orm = _sqlserverFixture.SqlServer; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guidnullable_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guidnullable_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - //update all - newid = Guid.NewGuid(); - item.guidnullable_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + //update all + newid = Guid.NewGuid(); + item.guidnullable_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - item.guidnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + item.guidnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guidnullable_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guidnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.guidnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.guidnullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerAdo/SqlServerAdoTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerAdo/SqlServerAdoTest.cs index b9559070..95a6006c 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerAdo/SqlServerAdoTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerAdo/SqlServerAdoTest.cs @@ -3,91 +3,101 @@ using FreeSql.Tests.DataContext.SqlServer; using System; using Xunit; -namespace FreeSql.Tests.SqlServer { - [Collection("SqlServerCollection")] - public class SqlServerAdoTest - { - SqlServerFixture _sqlserverFixture; +namespace FreeSql.Tests.SqlServer +{ + [Collection("SqlServerCollection")] + public class SqlServerAdoTest + { + SqlServerFixture _sqlserverFixture; - public SqlServerAdoTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public SqlServerAdoTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - [Fact] - public void Pool() { - var t1 = _sqlserverFixture.SqlServer.Ado.MasterPool.StatisticsFullily; - } + [Fact] + public void Pool() + { + var t1 = _sqlserverFixture.SqlServer.Ado.MasterPool.StatisticsFullily; + } - [Fact] - public void SlavePools() { - var t2 = _sqlserverFixture.SqlServer.Ado.SlavePools.Count; - } + [Fact] + public void SlavePools() + { + var t2 = _sqlserverFixture.SqlServer.Ado.SlavePools.Count; + } - [Fact] - public void ExecuteReader() { - - } - [Fact] - public void ExecuteArray() { - - } - [Fact] - public void ExecuteNonQuery() { - - } - [Fact] - public void ExecuteScalar() { - - } + [Fact] + public void ExecuteReader() + { - [Fact] - public void Query() { + } + [Fact] + public void ExecuteArray() + { - //var tt1 = _sqlserverFixture.SqlServer.Select() - // .LeftJoin(a => a.ParentId == a.Parent.Id) - // .ToSql(a => new { a.Id, a.Title }); + } + [Fact] + public void ExecuteNonQuery() + { - //var tt2result = _sqlserverFixture.SqlServer.Select() - // .LeftJoin(a => a.ParentId == a.Parent.Id) - // .ToList(a => new { a.Id, a.Title }); + } + [Fact] + public void ExecuteScalar() + { - //var tt = _sqlserverFixture.SqlServer.Select() - // .LeftJoin((a, b) => b.Id == a.Id) - // .ToSql(a => new { a.Id, a.Title }); + } - //var ttresult = _sqlserverFixture.SqlServer.Select() - // .LeftJoin((a, b) => b.Id == a.Id) - // .ToList(a => new { a.Id, a.Title }); + [Fact] + public void Query() + { - var tnsql1 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(1, 3).ToSql(a => a.Id); - var tnsql2 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(2, 3).ToSql(a => a.Id); + //var tt1 = _sqlserverFixture.SqlServer.Select() + // .LeftJoin(a => a.ParentId == a.Parent.Id) + // .ToSql(a => new { a.Id, a.Title }); - var tn1 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(1, 3).ToList(a => a.Id); - var tn2 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(2, 3).ToList(a => a.Id); + //var tt2result = _sqlserverFixture.SqlServer.Select() + // .LeftJoin(a => a.ParentId == a.Parent.Id) + // .ToList(a => new { a.Id, a.Title }); - var t3 = _sqlserverFixture.SqlServer.Ado.Query("select * from xxx"); + //var tt = _sqlserverFixture.SqlServer.Select() + // .LeftJoin((a, b) => b.Id == a.Id) + // .ToSql(a => new { a.Id, a.Title }); - var t4 = _sqlserverFixture.SqlServer.Ado.Query<(int, int, string, string DateTime)>("select * from xxx"); + //var ttresult = _sqlserverFixture.SqlServer.Select() + // .LeftJoin((a, b) => b.Id == a.Id) + // .ToList(a => new { a.Id, a.Title }); - var t5 = _sqlserverFixture.SqlServer.Ado.Query(System.Data.CommandType.Text, "select * from xxx where Id = @Id", - new System.Data.SqlClient.SqlParameter("Id", 1)); - } + var tnsql1 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(1, 3).ToSql(a => a.Id); + var tnsql2 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(2, 3).ToSql(a => a.Id); - [Fact] - public void QueryMultipline() { - var tnsql1 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(1, 3).ToSql(a => a.Id); + var tn1 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(1, 3).ToList(a => a.Id); + var tn2 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(2, 3).ToList(a => a.Id); - var t3 = _sqlserverFixture.SqlServer.Ado.Query("select * from xxx; select * from xxx; select * from xxx"); - } + var t3 = _sqlserverFixture.SqlServer.Ado.Query("select * from xxx"); - class xxx { - public int Id { get; set; } - public int ParentId { get; set; } - public xxx Parent { get; set; } - public string Title { get; set; } - public string Url { get; set; } - public DateTime Create_time { get; set; } - } - } + var t4 = _sqlserverFixture.SqlServer.Ado.Query<(int, int, string, string DateTime)>("select * from xxx"); + + var t5 = _sqlserverFixture.SqlServer.Ado.Query(System.Data.CommandType.Text, "select * from xxx where Id = @Id", + new System.Data.SqlClient.SqlParameter("Id", 1)); + } + + [Fact] + public void QueryMultipline() + { + var tnsql1 = _sqlserverFixture.SqlServer.Select().Where(a => a.Id > 0).Where(b => b.Title != null).Page(1, 3).ToSql(a => a.Id); + + var t3 = _sqlserverFixture.SqlServer.Ado.Query("select * from xxx; select * from xxx; select * from xxx"); + } + + class xxx + { + public int Id { get; set; } + public int ParentId { get; set; } + public xxx Parent { get; set; } + public string Title { get; set; } + public string Url { get; set; } + public DateTime Create_time { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs index 7d097c0d..e5d79172 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs @@ -7,366 +7,380 @@ using System.Linq; using System.Text; using Xunit; -namespace FreeSql.Tests.SqlServer { +namespace FreeSql.Tests.SqlServer +{ + + [Collection("SqlServerCollection")] + public class SqlServerCodeFirstTest + { + + SqlServerFixture _sqlserverFixture; + + public SqlServerCodeFirstTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } + + [Fact] + public void ı_ֶ() + { + var sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements<ı>(); + _sqlserverFixture.SqlServer.CodeFirst.SyncStructure<ı>(); + + var item = new ı + { + = "Ա", + ʱ = DateTime.Now + }; + Assert.Equal(1, _sqlserverFixture.SqlServer.Insert<ı>().AppendData(item).ExecuteAffrows()); + Assert.NotEqual(Guid.Empty, item.); + var item2 = _sqlserverFixture.SqlServer.Select<ı>().Where(a => a. == item.).First(); + Assert.NotNull(item2); + Assert.Equal(item., item2.); + Assert.Equal(item., item2.); + } + class ı + { + [Column(IsPrimary = true)] + public Guid { get; set; } + + public string { get; set; } + + public DateTime ʱ { get; set; } + } + + + [Fact] + public void AddUniques() + { + var sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); + _sqlserverFixture.SqlServer.CodeFirst.SyncStructure(); + } + [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] + class AddUniquesInfo + { + public Guid id { get; set; } + [Column(Unique = "uk_phone")] + public string phone { get; set; } + + [Column(Unique = "uk_group_index, uk_group_index22")] + public string group { get; set; } + [Column(Unique = "uk_group_index")] + public int index { get; set; } + [Column(Unique = "uk_group_index22")] + public string index22 { get; set; } + } + + [Fact] + public void AddField() + { + var sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); + + var id = _sqlserverFixture.SqlServer.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); + } + + [Table(Name = "dbo2.TopicAddField", OldName = "tedb1.dbo.TopicAddField")] + public class TopicAddField + { + [Column(IsIdentity = true)] + public int Id { get; set; } + + public int name { get; set; } = 3000; + + [Column(DbType = "varchar(200) not null", OldName = "title")] + public string title222 { get; set; } = "333"; + + [Column(DbType = "varchar(200) not null")] + public string title222333 { get; set; } = "xxx"; + + [Column(DbType = "varchar(100) not null", OldName = "title122333aaa")] + public string titleaaa { get; set; } = "fsdf"; + + [Column(IsIgnore = true)] + public DateTime ct { get; set; } = DateTime.Now; + } + + [Fact] + public void GetComparisonDDLStatements() + { + + var sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); + + sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); + } + + IInsert insert => _sqlserverFixture.SqlServer.Insert(); + ISelect select => _sqlserverFixture.SqlServer.Select(); + + [Fact] + public void CurdAllField() + { + var item = new TableAllType { }; + item.Id = (int)insert.AppendData(item).ExecuteIdentity(); + + var newitem = select.Where(a => a.Id == item.Id).ToOne(); + + var item2 = new TableAllType + { + testFieldBool = true, + testFieldBoolNullable = true, + testFieldByte = byte.MaxValue, + testFieldByteNullable = byte.MinValue, + testFieldBytes = Encoding.GetEncoding("gb2312").GetBytes("й"), + testFieldDateTime = DateTime.Now, + testFieldDateTimeNullable = DateTime.Now.AddHours(1), + testFieldDateTimeNullableOffset = new DateTimeOffset(DateTime.Now.AddHours(1), TimeSpan.FromHours(8)), + testFieldDateTimeOffset = new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(8)), + testFieldDecimal = 998.99M, + testFieldDecimalNullable = 999.12M, + testFieldDouble = 99.199, + testFieldDoubleNullable = 99.211, + testFieldEnum1 = TableAllTypeEnumType1.e2, + testFieldEnum1Nullable = TableAllTypeEnumType1.e3, + testFieldEnum2 = TableAllTypeEnumType2.f3, + testFieldEnum2Nullable = TableAllTypeEnumType2.f2, + testFieldFloat = 0.99F, + testFieldFloatNullable = 0.11F, + testFieldGuid = Guid.NewGuid(), + testFieldGuidNullable = Guid.NewGuid(), + testFieldInt = int.MaxValue, + testFieldIntNullable = int.MinValue, + testFieldLong = long.MaxValue, + testFieldSByte = sbyte.MaxValue, + testFieldSByteNullable = sbyte.MinValue, + testFieldShort = short.MaxValue, + testFieldShortNullable = short.MinValue, + testFieldString = "йstring", + testFieldTimeSpan = TimeSpan.FromSeconds(999), + testFieldTimeSpanNullable = TimeSpan.FromSeconds(30), + testFieldUInt = uint.MaxValue, + testFieldUIntNullable = uint.MinValue, + testFieldULong = ulong.MaxValue, + testFieldULongNullable = ulong.MinValue, + testFieldUShort = ushort.MaxValue, + testFieldUShortNullable = ushort.MinValue, + testFielLongNullable = long.MinValue + }; - [Collection("SqlServerCollection")] - public class SqlServerCodeFirstTest { - - SqlServerFixture _sqlserverFixture; - - public SqlServerCodeFirstTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } - - [Fact] - public void ı_ֶ() { - var sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements<ı>(); - _sqlserverFixture.SqlServer.CodeFirst.SyncStructure<ı>(); - - var item = new ı { - = "Ա", - ʱ = DateTime.Now - }; - Assert.Equal(1, _sqlserverFixture.SqlServer.Insert<ı>().AppendData(item).ExecuteAffrows()); - Assert.NotEqual(Guid.Empty, item.); - var item2 = _sqlserverFixture.SqlServer.Select<ı>().Where(a => a. == item.).First(); - Assert.NotNull(item2); - Assert.Equal(item., item2.); - Assert.Equal(item., item2.); - } - class ı { - [Column(IsPrimary = true)] - public Guid { get; set; } - - public string { get; set; } - - public DateTime ʱ { get; set; } - } - - - [Fact] - public void AddUniques() { - var sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); - _sqlserverFixture.SqlServer.CodeFirst.SyncStructure(); - } - [Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")] - class AddUniquesInfo { - public Guid id { get; set; } - [Column(Unique = "uk_phone")] - public string phone { get; set; } - - [Column(Unique = "uk_group_index, uk_group_index22")] - public string group { get; set; } - [Column(Unique = "uk_group_index")] - public int index { get; set; } - [Column(Unique = "uk_group_index22")] - public string index22 { get; set; } - } - - [Fact] - public void AddField() { - var sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); - - var id = _sqlserverFixture.SqlServer.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); - } - - [Table(Name = "dbo2.TopicAddField", OldName = "tedb1.dbo.TopicAddField")] - public class TopicAddField { - [Column(IsIdentity = true)] - public int Id { get; set; } - - public int name { get; set; } = 3000; - - [Column(DbType = "varchar(200) not null", OldName = "title")] - public string title222 { get; set; } = "333"; - - [Column(DbType = "varchar(200) not null")] - public string title222333 { get; set; } = "xxx"; - - [Column(DbType = "varchar(100) not null", OldName = "title122333aaa")] - public string titleaaa { get; set; } = "fsdf"; - - [Column(IsIgnore = true)] - public DateTime ct { get; set; } = DateTime.Now; - } - - [Fact] - public void GetComparisonDDLStatements() { + var sqlPar = insert.AppendData(item2).ToSql(); + var sqlText = insert.AppendData(item2).NoneParameter().ToSql(); - var sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); - - sql = _sqlserverFixture.SqlServer.CodeFirst.GetComparisonDDLStatements(); - } + var item3 = insert.AppendData(item2).ExecuteInserted(); + var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); - IInsert insert => _sqlserverFixture.SqlServer.Insert(); - ISelect select => _sqlserverFixture.SqlServer.Select(); + var items = select.ToList(); + } - [Fact] - public void CurdAllField() { - var item = new TableAllType { }; - item.Id = (int)insert.AppendData(item).ExecuteIdentity(); + [JsonObject(MemberSerialization.OptIn), Table(Name = "dbo.tb_alltype")] + public partial class Tb_alltype + { - var newitem = select.Where(a => a.Id == item.Id).ToOne(); + [JsonProperty, Column(Name = "Id", DbType = "int", IsPrimary = true, IsIdentity = true)] + public int Id { get; set; } - var item2 = new TableAllType { - testFieldBool = true, - testFieldBoolNullable = true, - testFieldByte = byte.MaxValue, - testFieldByteNullable = byte.MinValue, - testFieldBytes = Encoding.GetEncoding("gb2312").GetBytes("й"), - testFieldDateTime = DateTime.Now, - testFieldDateTimeNullable = DateTime.Now.AddHours(1), - testFieldDateTimeNullableOffset = new DateTimeOffset(DateTime.Now.AddHours(1), TimeSpan.FromHours(8)), - testFieldDateTimeOffset = new DateTimeOffset(DateTime.Now, TimeSpan.FromHours(8)), - testFieldDecimal = 998.99M, - testFieldDecimalNullable = 999.12M, - testFieldDouble = 99.199, - testFieldDoubleNullable = 99.211, - testFieldEnum1 = TableAllTypeEnumType1.e2, - testFieldEnum1Nullable = TableAllTypeEnumType1.e3, - testFieldEnum2 = TableAllTypeEnumType2.f3, - testFieldEnum2Nullable = TableAllTypeEnumType2.f2, - testFieldFloat = 0.99F, - testFieldFloatNullable = 0.11F, - testFieldGuid = Guid.NewGuid(), - testFieldGuidNullable = Guid.NewGuid(), - testFieldInt = int.MaxValue, - testFieldIntNullable = int.MinValue, - testFieldLong = long.MaxValue, - testFieldSByte = sbyte.MaxValue, - testFieldSByteNullable = sbyte.MinValue, - testFieldShort = short.MaxValue, - testFieldShortNullable = short.MinValue, - testFieldString = "йstring", - testFieldTimeSpan = TimeSpan.FromSeconds(999), - testFieldTimeSpanNullable = TimeSpan.FromSeconds(30), - testFieldUInt = uint.MaxValue, - testFieldUIntNullable = uint.MinValue, - testFieldULong = ulong.MaxValue, - testFieldULongNullable = ulong.MinValue, - testFieldUShort = ushort.MaxValue, - testFieldUShortNullable = ushort.MinValue, - testFielLongNullable = long.MinValue - }; - var sqlPar = insert.AppendData(item2).ToSql(); - var sqlText = insert.AppendData(item2).NoneParameter().ToSql(); + [JsonProperty, Column(Name = "testFieldBool1111", DbType = "bit")] + public bool TestFieldBool1111 { get; set; } - var item3 = insert.AppendData(item2).ExecuteInserted(); - var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); - var items = select.ToList(); - } + [JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit", IsNullable = true)] + public bool? TestFieldBoolNullable { get; set; } - [JsonObject(MemberSerialization.OptIn), Table(Name = "dbo.tb_alltype")] - public partial class Tb_alltype { - [JsonProperty, Column(Name = "Id", DbType = "int", IsPrimary = true, IsIdentity = true)] - public int Id { get; set; } + [JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint")] + public sbyte TestFieldByte { get; set; } - [JsonProperty, Column(Name = "testFieldBool1111", DbType = "bit")] - public bool TestFieldBool1111 { get; set; } + [JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint", IsNullable = true)] + public sbyte? TestFieldByteNullable { get; set; } - [JsonProperty, Column(Name = "testFieldBoolNullable", DbType = "bit", IsNullable = true)] - public bool? TestFieldBoolNullable { get; set; } + [JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)] + public byte[] TestFieldBytes { get; set; } - [JsonProperty, Column(Name = "testFieldByte", DbType = "tinyint")] - public sbyte TestFieldByte { get; set; } + [JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")] + public DateTime TestFieldDateTime { get; set; } - [JsonProperty, Column(Name = "testFieldByteNullable", DbType = "tinyint", IsNullable = true)] - public sbyte? TestFieldByteNullable { get; set; } + [JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)] + public DateTime? TestFieldDateTimeNullable { get; set; } - [JsonProperty, Column(Name = "testFieldBytes", DbType = "varbinary(255)", IsNullable = true)] - public byte[] TestFieldBytes { get; set; } + [JsonProperty, Column(Name = "testFieldDateTimeNullableOffset", DbType = "datetimeoffset", IsNullable = true)] + public DateTime? TestFieldDateTimeNullableOffset { get; set; } - [JsonProperty, Column(Name = "testFieldDateTime", DbType = "datetime")] - public DateTime TestFieldDateTime { get; set; } + [JsonProperty, Column(Name = "testFieldDateTimeOffset", DbType = "datetimeoffset")] + public DateTime TestFieldDateTimeOffset { get; set; } - [JsonProperty, Column(Name = "testFieldDateTimeNullable", DbType = "datetime", IsNullable = true)] - public DateTime? TestFieldDateTimeNullable { get; set; } + [JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")] + public decimal TestFieldDecimal { get; set; } - [JsonProperty, Column(Name = "testFieldDateTimeNullableOffset", DbType = "datetimeoffset", IsNullable = true)] - public DateTime? TestFieldDateTimeNullableOffset { get; set; } + [JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)] + public decimal? TestFieldDecimalNullable { get; set; } - [JsonProperty, Column(Name = "testFieldDateTimeOffset", DbType = "datetimeoffset")] - public DateTime TestFieldDateTimeOffset { get; set; } + [JsonProperty, Column(Name = "testFieldDouble", DbType = "float")] + public double TestFieldDouble { get; set; } - [JsonProperty, Column(Name = "testFieldDecimal", DbType = "decimal(10,2)")] - public decimal TestFieldDecimal { get; set; } + [JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "float", IsNullable = true)] + public double? TestFieldDoubleNullable { get; set; } - [JsonProperty, Column(Name = "testFieldDecimalNullable", DbType = "decimal(10,2)", IsNullable = true)] - public decimal? TestFieldDecimalNullable { get; set; } + [JsonProperty, Column(Name = "testFieldEnum1", DbType = "int")] + public int TestFieldEnum1 { get; set; } - [JsonProperty, Column(Name = "testFieldDouble", DbType = "float")] - public double TestFieldDouble { get; set; } + [JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "int", IsNullable = true)] + public int? TestFieldEnum1Nullable { get; set; } - [JsonProperty, Column(Name = "testFieldDoubleNullable", DbType = "float", IsNullable = true)] - public double? TestFieldDoubleNullable { get; set; } + [JsonProperty, Column(Name = "testFieldEnum2", DbType = "bigint")] + public long TestFieldEnum2 { get; set; } - [JsonProperty, Column(Name = "testFieldEnum1", DbType = "int")] - public int TestFieldEnum1 { get; set; } + [JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "bigint", IsNullable = true)] + public long? TestFieldEnum2Nullable { get; set; } - [JsonProperty, Column(Name = "testFieldEnum1Nullable", DbType = "int", IsNullable = true)] - public int? TestFieldEnum1Nullable { get; set; } + [JsonProperty, Column(Name = "testFieldFloat", DbType = "real")] + public float TestFieldFloat { get; set; } - [JsonProperty, Column(Name = "testFieldEnum2", DbType = "bigint")] - public long TestFieldEnum2 { get; set; } + [JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "real", IsNullable = true)] + public float? TestFieldFloatNullable { get; set; } - [JsonProperty, Column(Name = "testFieldEnum2Nullable", DbType = "bigint", IsNullable = true)] - public long? TestFieldEnum2Nullable { get; set; } + [JsonProperty, Column(Name = "testFieldGuid", DbType = "uniqueidentifier")] + public Guid TestFieldGuid { get; set; } - [JsonProperty, Column(Name = "testFieldFloat", DbType = "real")] - public float TestFieldFloat { get; set; } + [JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "uniqueidentifier", IsNullable = true)] + public Guid? TestFieldGuidNullable { get; set; } - [JsonProperty, Column(Name = "testFieldFloatNullable", DbType = "real", IsNullable = true)] - public float? TestFieldFloatNullable { get; set; } + [JsonProperty, Column(Name = "testFieldInt", DbType = "int")] + public int TestFieldInt { get; set; } - [JsonProperty, Column(Name = "testFieldGuid", DbType = "uniqueidentifier")] - public Guid TestFieldGuid { get; set; } + [JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int", IsNullable = true)] + public int? TestFieldIntNullable { get; set; } - [JsonProperty, Column(Name = "testFieldGuidNullable", DbType = "uniqueidentifier", IsNullable = true)] - public Guid? TestFieldGuidNullable { get; set; } + [JsonProperty, Column(Name = "testFieldLong", DbType = "bigint")] + public long TestFieldLong { get; set; } - [JsonProperty, Column(Name = "testFieldInt", DbType = "int")] - public int TestFieldInt { get; set; } + [JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint")] + public sbyte TestFieldSByte { get; set; } - [JsonProperty, Column(Name = "testFieldIntNullable", DbType = "int", IsNullable = true)] - public int? TestFieldIntNullable { get; set; } + [JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint", IsNullable = true)] + public sbyte? TestFieldSByteNullable { get; set; } - [JsonProperty, Column(Name = "testFieldLong", DbType = "bigint")] - public long TestFieldLong { get; set; } + [JsonProperty, Column(Name = "testFieldShort", DbType = "smallint")] + public short TestFieldShort { get; set; } - [JsonProperty, Column(Name = "testFieldSByte", DbType = "tinyint")] - public sbyte TestFieldSByte { get; set; } + [JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint", IsNullable = true)] + public short? TestFieldShortNullable { get; set; } - [JsonProperty, Column(Name = "testFieldSByteNullable", DbType = "tinyint", IsNullable = true)] - public sbyte? TestFieldSByteNullable { get; set; } + [JsonProperty, Column(Name = "testFieldString", DbType = "nvarchar(255)", IsNullable = true)] + public string TestFieldString { get; set; } - [JsonProperty, Column(Name = "testFieldShort", DbType = "smallint")] - public short TestFieldShort { get; set; } + [JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")] + public TimeSpan TestFieldTimeSpan { get; set; } - [JsonProperty, Column(Name = "testFieldShortNullable", DbType = "smallint", IsNullable = true)] - public short? TestFieldShortNullable { get; set; } + [JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)] + public TimeSpan? TestFieldTimeSpanNullable { get; set; } - [JsonProperty, Column(Name = "testFieldString", DbType = "nvarchar(255)", IsNullable = true)] - public string TestFieldString { get; set; } + [JsonProperty, Column(Name = "testFieldUInt", DbType = "int")] + public int TestFieldUInt { get; set; } - [JsonProperty, Column(Name = "testFieldTimeSpan", DbType = "time")] - public TimeSpan TestFieldTimeSpan { get; set; } + [JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int", IsNullable = true)] + public int? TestFieldUIntNullable { get; set; } - [JsonProperty, Column(Name = "testFieldTimeSpanNullable", DbType = "time", IsNullable = true)] - public TimeSpan? TestFieldTimeSpanNullable { get; set; } + [JsonProperty, Column(Name = "testFieldULong", DbType = "bigint")] + public long TestFieldULong { get; set; } - [JsonProperty, Column(Name = "testFieldUInt", DbType = "int")] - public int TestFieldUInt { get; set; } + [JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint", IsNullable = true)] + public long? TestFieldULongNullable { get; set; } - [JsonProperty, Column(Name = "testFieldUIntNullable", DbType = "int", IsNullable = true)] - public int? TestFieldUIntNullable { get; set; } + [JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint")] + public short TestFieldUShort { get; set; } - [JsonProperty, Column(Name = "testFieldULong", DbType = "bigint")] - public long TestFieldULong { get; set; } + [JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint", IsNullable = true)] + public short? TestFieldUShortNullable { get; set; } - [JsonProperty, Column(Name = "testFieldULongNullable", DbType = "bigint", IsNullable = true)] - public long? TestFieldULongNullable { get; set; } + [JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint", IsNullable = true)] + public long? TestFielLongNullable { get; set; } + } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - [JsonProperty, Column(Name = "testFieldUShort", DbType = "smallint")] - public short TestFieldUShort { get; set; } + [Column(Name = "testFieldBool1111")] + public bool testFieldBool { get; set; } + public sbyte testFieldSByte { get; set; } + public short testFieldShort { get; set; } + public int testFieldInt { get; set; } + public long testFieldLong { get; set; } + public byte testFieldByte { get; set; } + public ushort testFieldUShort { get; set; } + public uint testFieldUInt { get; set; } + public ulong testFieldULong { get; set; } + public double testFieldDouble { get; set; } + public float testFieldFloat { get; set; } + public decimal testFieldDecimal { get; set; } + public TimeSpan testFieldTimeSpan { get; set; } + public DateTime testFieldDateTime { get; set; } + public DateTimeOffset testFieldDateTimeOffset { get; set; } + public byte[] testFieldBytes { get; set; } + public string testFieldString { get; set; } + public Guid testFieldGuid { get; set; } + public bool? testFieldBoolNullable { get; set; } + public sbyte? testFieldSByteNullable { get; set; } + public short? testFieldShortNullable { get; set; } + public int? testFieldIntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? testFieldByteNullable { get; set; } + public ushort? testFieldUShortNullable { get; set; } + public uint? testFieldUIntNullable { get; set; } + public ulong? testFieldULongNullable { get; set; } + public double? testFieldDoubleNullable { get; set; } + public float? testFieldFloatNullable { get; set; } + public decimal? testFieldDecimalNullable { get; set; } + public TimeSpan? testFieldTimeSpanNullable { get; set; } + public DateTime? testFieldDateTimeNullable { get; set; } + public DateTimeOffset? testFieldDateTimeNullableOffset { get; set; } + public Guid? testFieldGuidNullable { get; set; } - [JsonProperty, Column(Name = "testFieldUShortNullable", DbType = "smallint", IsNullable = true)] - public short? TestFieldUShortNullable { get; set; } + public TableAllTypeEnumType1 testFieldEnum1 { get; set; } + public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } + public TableAllTypeEnumType2 testFieldEnum2 { get; set; } + public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } + } - - [JsonProperty, Column(Name = "testFielLongNullable", DbType = "bigint", IsNullable = true)] - public long? TestFielLongNullable { get; set; } - } - - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - - [Column(Name = "testFieldBool1111")] - public bool testFieldBool { get; set; } - public sbyte testFieldSByte { get; set; } - public short testFieldShort { get; set; } - public int testFieldInt { get; set; } - public long testFieldLong { get; set; } - public byte testFieldByte { get; set; } - public ushort testFieldUShort { get; set; } - public uint testFieldUInt { get; set; } - public ulong testFieldULong { get; set; } - public double testFieldDouble { get; set; } - public float testFieldFloat { get; set; } - public decimal testFieldDecimal { get; set; } - public TimeSpan testFieldTimeSpan { get; set; } - public DateTime testFieldDateTime { get; set; } - public DateTimeOffset testFieldDateTimeOffset { get; set; } - public byte[] testFieldBytes { get; set; } - public string testFieldString { get; set; } - public Guid testFieldGuid { get; set; } - - public bool? testFieldBoolNullable { get; set; } - public sbyte? testFieldSByteNullable { get; set; } - public short? testFieldShortNullable { get; set; } - public int? testFieldIntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? testFieldByteNullable { get; set; } - public ushort? testFieldUShortNullable { get; set; } - public uint? testFieldUIntNullable { get; set; } - public ulong? testFieldULongNullable { get; set; } - public double? testFieldDoubleNullable { get; set; } - public float? testFieldFloatNullable { get; set; } - public decimal? testFieldDecimalNullable { get; set; } - public TimeSpan? testFieldTimeSpanNullable { get; set; } - public DateTime? testFieldDateTimeNullable { get; set; } - public DateTimeOffset? testFieldDateTimeNullableOffset { get; set; } - public Guid? testFieldGuidNullable { get; set; } - - public TableAllTypeEnumType1 testFieldEnum1 { get; set; } - public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } - public TableAllTypeEnumType2 testFieldEnum2 { get; set; } - public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } - } - - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerDbFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerDbFirstTest.cs index 1cac9136..43227e68 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerDbFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerDbFirstTest.cs @@ -3,29 +3,33 @@ using FreeSql.Tests.DataContext.SqlServer; using System; using Xunit; -namespace FreeSql.Tests.SqlServer { - [Collection("SqlServerCollection")] - public class SqlServerDbFirstTest { +namespace FreeSql.Tests.SqlServer +{ + [Collection("SqlServerCollection")] + public class SqlServerDbFirstTest + { - SqlServerFixture _sqlserverFixture; + SqlServerFixture _sqlserverFixture; - public SqlServerDbFirstTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public SqlServerDbFirstTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - [Fact] - public void GetDatabases() { + [Fact] + public void GetDatabases() + { - var t1 = _sqlserverFixture.SqlServer.DbFirst.GetDatabases(); + var t1 = _sqlserverFixture.SqlServer.DbFirst.GetDatabases(); - } + } - [Fact] - public void GetTablesByDatabase() { + [Fact] + public void GetTablesByDatabase() + { - var t2 = _sqlserverFixture.SqlServer.DbFirst.GetTablesByDatabase(); + var t2 = _sqlserverFixture.SqlServer.DbFirst.GetTablesByDatabase(); - } - } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/ConvertTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/ConvertTest.cs index f5ed9207..f8abe2ed 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/ConvertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/ConvertTest.cs @@ -5,151 +5,174 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServerExpression { - [Collection("SqlServerCollection")] - public class ConvertTest { +namespace FreeSql.Tests.SqlServerExpression +{ + [Collection("SqlServerCollection")] + public class ConvertTest + { - SqlServerFixture _sqlserverFixture; + SqlServerFixture _sqlserverFixture; - public ConvertTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public ConvertTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - ISelect select => _sqlserverFixture.SqlServer.Select(); + ISelect select => _sqlserverFixture.SqlServer.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void ToBoolean() { - var data = new List(); - data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); - data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); - } - [Fact] - public void ToByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); - data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); - } - [Fact] - public void ToChar() { - var data = new List(); - data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); - data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); - } - [Fact] - public void ToDateTime() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); - } - [Fact] - public void ToDecimal() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToDouble() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt32() { - var data = new List(); - data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); - data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToSByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); - data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); - } - [Fact] - public void ToSingle() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); - data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); - } - [Fact] - public void ToUInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt32() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); - } + [Fact] + public void ToBoolean() + { + var data = new List(); + data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); + data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); + } + [Fact] + public void ToByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); + data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); + } + [Fact] + public void ToChar() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); + data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); + } + [Fact] + public void ToDateTime() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); + } + [Fact] + public void ToDecimal() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToDouble() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt32() + { + var data = new List(); + data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); + data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToSByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); + data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); + } + [Fact] + public void ToSingle() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); + data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); + } + [Fact] + public void ToUInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt32() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); + } - [Fact] - public void Guid_Parse() { - var data = new List(); - data.Add(select.Where(a => Guid.Parse(Guid.NewGuid().ToString()) == Guid.Empty).ToList()); - } + [Fact] + public void Guid_Parse() + { + var data = new List(); + data.Add(select.Where(a => Guid.Parse(Guid.NewGuid().ToString()) == Guid.Empty).ToList()); + } - [Fact] - public void Guid_NewGuid() { - var data = new List(); - data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); - } + [Fact] + public void Guid_NewGuid() + { + var data = new List(); + data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); + } - [Fact] - public void Random() { - var data = new List(); - data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); - data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); - } - } + [Fact] + public void Random() + { + var data = new List(); + data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); + data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/DateTimeTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/DateTimeTest.cs index ef9d4708..1f36c181 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/DateTimeTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/DateTimeTest.cs @@ -5,288 +5,326 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServerExpression { - [Collection("SqlServerCollection")] - public class DateTimeTest - { - SqlServerFixture _sqlserverFixture; +namespace FreeSql.Tests.SqlServerExpression +{ + [Collection("SqlServerCollection")] + public class DateTimeTest + { + SqlServerFixture _sqlserverFixture; - public DateTimeTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public DateTimeTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - ISelect select => _sqlserverFixture.SqlServer.Select(); + ISelect select => _sqlserverFixture.SqlServer.Select(); - [Table(Name = "tb_topic111333")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - [Table(Name = "TestTypeInfo333")] - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - public DateTime Time { get; set; } - } - [Table(Name = "TestTypeParentInfo23123")] - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic111333")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + [Table(Name = "TestTypeInfo333")] + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + public DateTime Time { get; set; } + } + [Table(Name = "TestTypeParentInfo23123")] + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - public DateTime Time2 { get; set; } - } - [Fact] - public void Now() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - } - [Fact] - public void UtcNow() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); - } - [Fact] - public void Date() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); + public List Types { get; set; } + public DateTime Time2 { get; set; } + } + [Fact] + public void Now() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + } + [Fact] + public void UtcNow() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); + } + [Fact] + public void Date() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); - } - [Fact] - public void TimeOfDay() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - } - [Fact] - public void DayOfWeek() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - } - [Fact] - public void Day() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); - } - [Fact] - public void DayOfYear() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); - } - [Fact] - public void Month() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); - } - [Fact] - public void Year() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); - } - [Fact] - public void Hour() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); - } - [Fact] - public void Minute() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); - } - [Fact] - public void Second() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); - } - [Fact] - public void Millisecond() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - } - [Fact] - public void AddDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); - } - [Fact] - public void AddHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); - } - [Fact] - public void AddMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); - } - [Fact] - public void AddMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); - } - [Fact] - public void AddMonths() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); - } - [Fact] - public void AddSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); - } - [Fact] - public void AddTicks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); - } - [Fact] - public void AddYears() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); + } + [Fact] + public void TimeOfDay() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + } + [Fact] + public void DayOfWeek() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + } + [Fact] + public void Day() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); + } + [Fact] + public void DayOfYear() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); + } + [Fact] + public void Month() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); + } + [Fact] + public void Year() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); + } + [Fact] + public void Hour() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); + } + [Fact] + public void Minute() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); + } + [Fact] + public void Second() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); + } + [Fact] + public void Millisecond() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + } + [Fact] + public void AddDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); + } + [Fact] + public void AddHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); + } + [Fact] + public void AddMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); + } + [Fact] + public void AddMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); + } + [Fact] + public void AddMonths() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); + } + [Fact] + public void AddSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); + } + [Fact] + public void AddTicks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); + } + [Fact] + public void AddYears() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - } - [Fact] - public void _ЧͬSubtract() { - var data = new List(); - data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + } + [Fact] + public void _ЧͬSubtract() + { + var data = new List(); + data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - } + data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + } - [Fact] - public void DateTime_Compare() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - } - [Fact] - public void DateTime_DaysInMonth() { - var data = new List(); - data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); - } - [Fact] - public void DateTime_Equals() { - var data = new List(); - data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); - } - [Fact] - public void DateTime_IsLeapYear() { - var data = new List(); - data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); - } - [Fact] - public void DateTime_Parse() { - var data = new List(); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); - } - } + [Fact] + public void DateTime_Compare() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + } + [Fact] + public void DateTime_DaysInMonth() + { + var data = new List(); + data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); + } + [Fact] + public void DateTime_Equals() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); + } + [Fact] + public void DateTime_IsLeapYear() + { + var data = new List(); + data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); + } + [Fact] + public void DateTime_Parse() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/MathTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/MathTest.cs index 7bab4502..87481aeb 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/MathTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/MathTest.cs @@ -5,137 +5,160 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServerExpression { - [Collection("SqlServerCollection")] - public class MathTest - { - SqlServerFixture _sqlserverFixture; +namespace FreeSql.Tests.SqlServerExpression +{ + [Collection("SqlServerCollection")] + public class MathTest + { + SqlServerFixture _sqlserverFixture; - public MathTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public MathTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - ISelect select => _sqlserverFixture.SqlServer.Select(); + ISelect select => _sqlserverFixture.SqlServer.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void PI() { - var data = new List(); - data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); - } - [Fact] - public void Abs() { - var data = new List(); - data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Sign() { - var data = new List(); - data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Floor() { - var data = new List(); - data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); - } - [Fact] - public void Ceiling() { - var data = new List(); - data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Round() { - var data = new List(); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); - } - [Fact] - public void Exp() { - var data = new List(); - data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log() { - //var data = new List(); - //data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log10() { - //var data = new List(); - //data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Pow() { - var data = new List(); - //data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sqrt() { - var data = new List(); - //data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Cos() { - var data = new List(); - //data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sin() { - var data = new List(); - //data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Tan() { - var data = new List(); - //data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Acos() { - var data = new List(); - //data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Asin() { - var data = new List(); - //data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan() { - var data = new List(); - //data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan2() { - var data = new List(); - //data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Truncate() { - var data = new List(); - data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); - } - } + [Fact] + public void PI() + { + var data = new List(); + data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); + } + [Fact] + public void Abs() + { + var data = new List(); + data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Sign() + { + var data = new List(); + data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Floor() + { + var data = new List(); + data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); + } + [Fact] + public void Ceiling() + { + var data = new List(); + data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Round() + { + var data = new List(); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); + } + [Fact] + public void Exp() + { + var data = new List(); + data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log() + { + //var data = new List(); + //data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log10() + { + //var data = new List(); + //data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Pow() + { + var data = new List(); + //data.Add(select.Where(a => Math.Pow(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sqrt() + { + var data = new List(); + //data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Cos() + { + var data = new List(); + //data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sin() + { + var data = new List(); + //data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Tan() + { + var data = new List(); + //data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Acos() + { + var data = new List(); + //data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Asin() + { + var data = new List(); + //data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan() + { + var data = new List(); + //data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan2() + { + var data = new List(); + //data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Truncate() + { + var data = new List(); + data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/OtherTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/OtherTest.cs index 9e480695..ef10ff43 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/OtherTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/OtherTest.cs @@ -5,113 +5,118 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServerExpression { - [Collection("SqlServerCollection")] - public class OtherTest { +namespace FreeSql.Tests.SqlServerExpression +{ + [Collection("SqlServerCollection")] + public class OtherTest + { - SqlServerFixture _sqlserverFixture; + SqlServerFixture _sqlserverFixture; - public OtherTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public OtherTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - ISelect select => _sqlserverFixture.SqlServer.Select(); + ISelect select => _sqlserverFixture.SqlServer.Select(); - [Fact] - public void Boolean() { - var t1 = select.Where(a => a.testFieldBool == true).ToList(); - var t2 = select.Where(a => a.testFieldBool != true).ToList(); - var t3 = select.Where(a => a.testFieldBool == false).ToList(); - var t4 = select.Where(a => !a.testFieldBool).ToList(); - var t5 = select.Where(a => a.testFieldBool).ToList(); + [Fact] + public void Boolean() + { + var t1 = select.Where(a => a.testFieldBool == true).ToList(); + var t2 = select.Where(a => a.testFieldBool != true).ToList(); + var t3 = select.Where(a => a.testFieldBool == false).ToList(); + var t4 = select.Where(a => !a.testFieldBool).ToList(); + var t5 = select.Where(a => a.testFieldBool).ToList(); - var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList(); - var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); - var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); - var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); - var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList(); - } + var t11 = select.Where(a => a.testFieldBoolNullable == true).ToList(); + var t22 = select.Where(a => a.testFieldBoolNullable != true).ToList(); + var t33 = select.Where(a => a.testFieldBoolNullable == false).ToList(); + var t44 = select.Where(a => !a.testFieldBoolNullable.Value).ToList(); + var t55 = select.Where(a => a.testFieldBoolNullable.Value).ToList(); + } - [Fact] - public void Array() { - IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); - var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); + [Fact] + public void Array() + { + IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); + var testlinq = select.Where(a => testlinqlist.Contains(a.testFieldInt)).ToList(); - //in not in - var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); - var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + //in not in + var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); + var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var inarray = new[] { 1, 2, 3 }; - var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); - var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); - var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); + var inarray = new[] { 1, 2, 3 }; + var sql1111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); + var sql1122 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); + var sql1133 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); - //in not in - var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); - var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + //in not in + var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); + var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.testFieldInt) == false).ToList(); + var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.testFieldInt)).ToList(); - var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); - var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); - var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); + var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); + var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt) == false).ToList(); + var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.testFieldInt)).ToList(); - var inarray2 = new List() { 1, 2, 3 }; - var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); - var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); - var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); - } + var inarray2 = new List() { 1, 2, 3 }; + var sql111111 = select.Where(a => inarray.Contains(a.testFieldInt)).ToList(); + var sql112222 = select.Where(a => inarray.Contains(a.testFieldInt) == false).ToList(); + var sql113333 = select.Where(a => !inarray.Contains(a.testFieldInt)).ToList(); + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - [Column(Name = "testFieldBool1111")] - public bool testFieldBool { get; set; } - public sbyte testFieldSByte { get; set; } - public short testFieldShort { get; set; } - public int testFieldInt { get; set; } - public long testFieldLong { get; set; } - public byte testFieldByte { get; set; } - public ushort testFieldUShort { get; set; } - public uint testFieldUInt { get; set; } - public ulong testFieldULong { get; set; } - public double testFieldDouble { get; set; } - public float testFieldFloat { get; set; } - public decimal testFieldDecimal { get; set; } - public TimeSpan testFieldTimeSpan { get; set; } - public DateTime testFieldDateTime { get; set; } - public DateTimeOffset testFieldDateTimeOffset { get; set; } - public byte[] testFieldBytes { get; set; } - public string testFieldString { get; set; } - public Guid testFieldGuid { get; set; } + [Column(Name = "testFieldBool1111")] + public bool testFieldBool { get; set; } + public sbyte testFieldSByte { get; set; } + public short testFieldShort { get; set; } + public int testFieldInt { get; set; } + public long testFieldLong { get; set; } + public byte testFieldByte { get; set; } + public ushort testFieldUShort { get; set; } + public uint testFieldUInt { get; set; } + public ulong testFieldULong { get; set; } + public double testFieldDouble { get; set; } + public float testFieldFloat { get; set; } + public decimal testFieldDecimal { get; set; } + public TimeSpan testFieldTimeSpan { get; set; } + public DateTime testFieldDateTime { get; set; } + public DateTimeOffset testFieldDateTimeOffset { get; set; } + public byte[] testFieldBytes { get; set; } + public string testFieldString { get; set; } + public Guid testFieldGuid { get; set; } - public bool? testFieldBoolNullable { get; set; } - public sbyte? testFieldSByteNullable { get; set; } - public short? testFieldShortNullable { get; set; } - public int? testFieldIntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? testFieldByteNullable { get; set; } - public ushort? testFieldUShortNullable { get; set; } - public uint? testFieldUIntNullable { get; set; } - public ulong? testFieldULongNullable { get; set; } - public double? testFieldDoubleNullable { get; set; } - public float? testFieldFloatNullable { get; set; } - public decimal? testFieldDecimalNullable { get; set; } - public TimeSpan? testFieldTimeSpanNullable { get; set; } - public DateTime? testFieldDateTimeNullable { get; set; } - public DateTimeOffset? testFieldDateTimeNullableOffset { get; set; } - public Guid? testFieldGuidNullable { get; set; } + public bool? testFieldBoolNullable { get; set; } + public sbyte? testFieldSByteNullable { get; set; } + public short? testFieldShortNullable { get; set; } + public int? testFieldIntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? testFieldByteNullable { get; set; } + public ushort? testFieldUShortNullable { get; set; } + public uint? testFieldUIntNullable { get; set; } + public ulong? testFieldULongNullable { get; set; } + public double? testFieldDoubleNullable { get; set; } + public float? testFieldFloatNullable { get; set; } + public decimal? testFieldDecimalNullable { get; set; } + public TimeSpan? testFieldTimeSpanNullable { get; set; } + public DateTime? testFieldDateTimeNullable { get; set; } + public DateTimeOffset? testFieldDateTimeNullableOffset { get; set; } + public Guid? testFieldGuidNullable { get; set; } - public TableAllTypeEnumType1 testFieldEnum1 { get; set; } - public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } - public TableAllTypeEnumType2 testFieldEnum2 { get; set; } - public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } - } + public TableAllTypeEnumType1 testFieldEnum1 { get; set; } + public TableAllTypeEnumType1? testFieldEnum1Nullable { get; set; } + public TableAllTypeEnumType2 testFieldEnum2 { get; set; } + public TableAllTypeEnumType2? testFieldEnum2Nullable { get; set; } + } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/StringTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/StringTest.cs index 1338612a..3cd5b5d9 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/StringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/StringTest.cs @@ -5,261 +5,285 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServerExpression { - [Collection("SqlServerCollection")] - public class StringTest { +namespace FreeSql.Tests.SqlServerExpression +{ + [Collection("SqlServerCollection")] + public class StringTest + { - SqlServerFixture _sqlserverFixture; + SqlServerFixture _sqlserverFixture; - public StringTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public StringTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - ISelect select => _sqlserverFixture.SqlServer.Select(); + ISelect select => _sqlserverFixture.SqlServer.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } - class TestEqualsGuid { - public Guid id { get; set; } - } + public List Types { get; set; } + } + class TestEqualsGuid + { + public Guid id { get; set; } + } - [Fact] - public void Equals__() { - var list = new List(); - list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); - list.Add(_sqlserverFixture.SqlServer.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); - } + [Fact] + public void Equals__() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); + list.Add(_sqlserverFixture.SqlServer.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); + } - [Fact] - public void Empty() { - var data = new List(); - data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); - } + [Fact] + public void Empty() + { + var data = new List(); + data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); + } - [Fact] - public void StartsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); + [Fact] + public void StartsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); - } - [Fact] - public void EndsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); + } + [Fact] + public void EndsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); - } - [Fact] - public void Contains() { - var list = new List(); - list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); + } + [Fact] + public void Contains() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); - } - [Fact] - public void ToLower() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); + } + [Fact] + public void ToLower() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); - } - [Fact] - public void ToUpper() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); + } + [Fact] + public void ToUpper() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); - } - [Fact] - public void Substring() { - var data = new List(); - data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); + } + [Fact] + public void Substring() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); - } - [Fact] - public void Length() { - var data = new List(); - data.Add(select.Where(a => a.Title.Length == 0).ToList()); - data.Add(select.Where(a => a.Title.Length == 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); + } + [Fact] + public void Length() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Length == 0).ToList()); + data.Add(select.Where(a => a.Title.Length == 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); - } - [Fact] - public void IndexOf() { - var data = new List(); - data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); + } + [Fact] + public void IndexOf() + { + var data = new List(); + data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - } - [Fact] - public void PadLeft() { - //var data = new List(); - //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); - //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); - //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); - //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + } + [Fact] + public void PadLeft() + { + //var data = new List(); + //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); + //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); + //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); + //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); - //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); - //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); - //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); - //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); - } - [Fact] - public void PadRight() { - //var data = new List(); - //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); - //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); - //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); - //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); + //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); + //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); + //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); + //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); + } + [Fact] + public void PadRight() + { + //var data = new List(); + //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); + //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); + //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); + //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); - //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); - //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); - //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); - //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); - } - [Fact] - public void Trim() { - var data = new List(); - data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); + //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); + //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); + //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); + } + [Fact] + public void Trim() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); - data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); - } - [Fact] - public void TrimStart() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); + } + [Fact] + public void TrimStart() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - } - [Fact] - public void TrimEnd() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + } + [Fact] + public void TrimEnd() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - } - [Fact] - public void Replace() { - var data = new List(); - data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + } + [Fact] + public void Replace() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - } - [Fact] - public void CompareTo() { - //var data = new List(); - //data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); - //data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); - //data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); - //data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + } + [Fact] + public void CompareTo() + { + //var data = new List(); + //data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); + //data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); + //data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); + //data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); - //data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); - //data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); - //data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); - //data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); - } + //data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); + //data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); + //data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); + //data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); + } - [Fact] - public void string_IsNullOrEmpty() { - var data = new List(); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); - //data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); - data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); - } - } + [Fact] + public void string_IsNullOrEmpty() + { + var data = new List(); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); + //data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); + data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/TimeSpanTest.cs b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/TimeSpanTest.cs index 7490b5ea..7d5b6779 100644 --- a/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/TimeSpanTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerExpression/TimeSpanTest.cs @@ -5,181 +5,214 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqlServerExpression { - [Collection("SqlServerCollection")] - public class TimeSpanTest { +namespace FreeSql.Tests.SqlServerExpression +{ + [Collection("SqlServerCollection")] + public class TimeSpanTest + { - SqlServerFixture _sqlserverFixture; + SqlServerFixture _sqlserverFixture; - public TimeSpanTest(SqlServerFixture sqlserverFixture) - { - _sqlserverFixture = sqlserverFixture; - } + public TimeSpanTest(SqlServerFixture sqlserverFixture) + { + _sqlserverFixture = sqlserverFixture; + } - ISelect select => _sqlserverFixture.SqlServer.Select(); + ISelect select => _sqlserverFixture.SqlServer.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } - [Fact] - public void Zero() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); - } - [Fact] - public void Days() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); - } - [Fact] - public void Hours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); - } - [Fact] - public void Milliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); - } - [Fact] - public void Minutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); - } - [Fact] - public void Seconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); - } - [Fact] - public void TotalDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); - } - [Fact] - public void TotalHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); - } - [Fact] - public void TotalMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); - } - [Fact] - public void TotalMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); - } - [Fact] - public void TotalSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); - } + public List Types { get; set; } + } + [Fact] + public void Zero() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); + } + [Fact] + public void Days() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); + } + [Fact] + public void Hours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); + } + [Fact] + public void Milliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); + } + [Fact] + public void Minutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); + } + [Fact] + public void Seconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); + } + [Fact] + public void TotalDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); + } + [Fact] + public void TotalHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); + } + [Fact] + public void TotalMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); + } + [Fact] + public void TotalMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); + } + [Fact] + public void TotalSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); + } - [Fact] - public void TimeSpan_Compare() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); - } - [Fact] - public void TimeSpan_Equals() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - } - [Fact] - public void TimeSpan_FromDays() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - } - [Fact] - public void TimeSpan_FromHours() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); - } - [Fact] - public void TimeSpan_FromMilliseconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); - } - [Fact] - public void TimeSpan_FromMinutes() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); - } - [Fact] - public void TimeSpan_FromSeconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); - } - [Fact] - public void TimeSpan_FromTicks() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); - } - [Fact] - public void TimeSpan_Parse() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); - } - } + [Fact] + public void TimeSpan_Compare() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); + } + [Fact] + public void TimeSpan_Equals() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + } + [Fact] + public void TimeSpan_FromDays() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + } + [Fact] + public void TimeSpan_FromHours() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); + } + [Fact] + public void TimeSpan_FromMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); + } + [Fact] + public void TimeSpan_FromMinutes() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); + } + [Fact] + public void TimeSpan_FromSeconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); + } + [Fact] + public void TimeSpan_FromTicks() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); + } + [Fact] + public void TimeSpan_Parse() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteDeleteTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteDeleteTest.cs index fca1ae13..8a58358e 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteDeleteTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteDeleteTest.cs @@ -4,86 +4,95 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.Sqlite { - public class SqliteDeleteTest { +namespace FreeSql.Tests.Sqlite +{ + public class SqliteDeleteTest + { - IDelete delete => g.sqlite.Delete(); //�������� + IDelete delete => g.sqlite.Delete(); //�������� - [Table(Name = "tb_topic22211")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } + [Table(Name = "tb_topic22211")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void Dywhere() { - Assert.Null(g.sqlite.Delete().ToSql()); - var sql = g.sqlite.Delete(new[] { 1, 2 }).ToSql(); - Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql); + [Fact] + public void Dywhere() + { + Assert.Null(g.sqlite.Delete().ToSql()); + var sql = g.sqlite.Delete(new[] { 1, 2 }).ToSql(); + Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql); - sql = g.sqlite.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); - Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql); + sql = g.sqlite.Delete(new Topic { Id = 1, Title = "test" }).ToSql(); + Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql); - sql = g.sqlite.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); - Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql); + sql = g.sqlite.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); + Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql); - sql = g.sqlite.Delete(new { id = 1 }).ToSql(); - Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql); - } + sql = g.sqlite.Delete(new { id = 1 }).ToSql(); + Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql); + } - [Fact] - public void Where() { - var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql); + [Fact] + public void Where() + { + var sql = delete.Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql); - sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (id = @id)", sql); + sql = delete.Where("id = @id", new { id = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (id = @id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = delete.Where(item).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = delete.Where(item).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = delete.Where(items).ToSql().Replace("\r\n", ""); - Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + sql = delete.Where(items).ToSql().Replace("\r\n", ""); + Assert.Equal("DELETE FROM \"tb_topic22211\" WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - var id = g.sqlite.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteIdentity(); - Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); - } - [Fact] - public void ExecuteDeleted() { + var id = g.sqlite.Insert(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteIdentity(); + Assert.Equal(1, delete.Where(a => a.Id == id).ExecuteAffrows()); + } + [Fact] + public void ExecuteDeleted() + { - //var item = g.Sqlite.Delete(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteInserted(); - //Assert.Equal(item[0].Id, delete.Where(a => a.Id == item[0].Id).ExecuteDeleted()[0].Id); - } + //var item = g.Sqlite.Delete(new Topic { Title = "xxxx", CreateTime = DateTime.Now }).ExecuteInserted(); + //Assert.Equal(item[0].Id, delete.Where(a => a.Id == item[0].Id).ExecuteDeleted()[0].Id); + } - [Fact] - public void AsTable() { - Assert.Null(g.sqlite.Delete().AsTable(a => "TopicAsTable").ToSql()); - var sql = g.sqlite.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql); + [Fact] + public void AsTable() + { + Assert.Null(g.sqlite.Delete().AsTable(a => "TopicAsTable").ToSql()); + var sql = g.sqlite.Delete(new[] { 1, 2 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql); - sql = g.sqlite.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"Id\" = 1)", sql); + sql = g.sqlite.Delete(new Topic { Id = 1, Title = "test" }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"Id\" = 1)", sql); - sql = g.sqlite.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql); + sql = g.sqlite.Delete(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"Id\" = 1 OR \"Id\" = 2)", sql); - sql = g.sqlite.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); - Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"Id\" = 1)", sql); - } - } + sql = g.sqlite.Delete(new { id = 1 }).AsTable(a => "TopicAsTable").ToSql(); + Assert.Equal("DELETE FROM \"TopicAsTable\" WHERE (\"Id\" = 1)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteInsertTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteInsertTest.cs index c400746d..57b3b869 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteInsertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteInsertTest.cs @@ -4,108 +4,118 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.Sqlite { - public class SqliteInsertTest { +namespace FreeSql.Tests.Sqlite +{ + public class SqliteInsertTest + { - IInsert insert => g.sqlite.Insert(); + IInsert insert => g.sqlite.Insert(); - [Table(Name = "tb_topic_insert")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } + [Table(Name = "tb_topic_insert")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void AppendData() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + [Fact] + public void AppendData() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - var sql = insert.AppendData(items.First()).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); + var sql = insert.AppendData(items.First()).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); - sql = insert.AppendData(items).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); + sql = insert.AppendData(items).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Title\") VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Title\") VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - } + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + } - [Fact] - public void InsertColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + [Fact] + public void InsertColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Title\") VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + var sql = insert.AppendData(items).InsertColumns(a => a.Title).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Title\") VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - } - [Fact] - public void IgnoreColumns() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + } + [Fact] + public void IgnoreColumns() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + var sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); - Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\") VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); - } - [Fact] - public void ExecuteAffrows() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); + Assert.Equal("INSERT INTO \"tb_topic_insert\"(\"Clicks\") VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); + } + [Fact] + public void ExecuteAffrows() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); - } - [Fact] - public void ExecuteIdentity() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + Assert.Equal(1, insert.AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, insert.AppendData(items).ExecuteAffrows()); + } + [Fact] + public void ExecuteIdentity() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); - } - [Fact] - public void ExecuteInserted() { - } + Assert.NotEqual(0, insert.AppendData(items.First()).ExecuteIdentity()); + } + [Fact] + public void ExecuteInserted() + { + } - [Fact] - public void AsTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); + [Fact] + public void AsTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newTitle{a}", Clicks = a * 100 }); - var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); + var sql = insert.AppendData(items.First()).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(@Clicks_0, @Title_0, @CreateTime_0)", sql); - sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); + sql = insert.AppendData(items).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\", \"CreateTime\") VALUES(@Clicks_0, @Title_0, @CreateTime_0), (@Clicks_1, @Title_1, @CreateTime_1), (@Clicks_2, @Title_2, @CreateTime_2), (@Clicks_3, @Title_3, @CreateTime_3), (@Clicks_4, @Title_4, @CreateTime_4), (@Clicks_5, @Title_5, @CreateTime_5), (@Clicks_6, @Title_6, @CreateTime_6), (@Clicks_7, @Title_7, @CreateTime_7), (@Clicks_8, @Title_8, @CreateTime_8), (@Clicks_9, @Title_9, @CreateTime_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Title\") VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Title\") VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Title\") VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => a.Title).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Title\") VALUES(@Title_0), (@Title_1), (@Title_2), (@Title_3), (@Title_4), (@Title_5), (@Title_6), (@Title_7), (@Title_8), (@Title_9)", sql); - sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).InsertColumns(a => new { a.Title, a.Clicks }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); + sql = insert.AppendData(items).IgnoreColumns(a => a.CreateTime).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\", \"Title\") VALUES(@Clicks_0, @Title_0), (@Clicks_1, @Title_1), (@Clicks_2, @Title_2), (@Clicks_3, @Title_3), (@Clicks_4, @Title_4), (@Clicks_5, @Title_5), (@Clicks_6, @Title_6), (@Clicks_7, @Title_7), (@Clicks_8, @Title_8), (@Clicks_9, @Title_9)", sql); - sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); - Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\") VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); - } - } + sql = insert.AppendData(items).IgnoreColumns(a => new { a.Title, a.CreateTime }).AsTable(a => "Topic_InsertAsTable").ToSql(); + Assert.Equal("INSERT INTO \"Topic_InsertAsTable\"(\"Clicks\") VALUES(@Clicks_0), (@Clicks_1), (@Clicks_2), (@Clicks_3), (@Clicks_4), (@Clicks_5), (@Clicks_6), (@Clicks_7), (@Clicks_8), (@Clicks_9)", sql); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteSelectTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteSelectTest.cs index de328f03..c943800d 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteSelectTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteSelectTest.cs @@ -4,1075 +4,1146 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.Sqlite { - public class SqliteSelectTest { - - ISelect select => g.sqlite.Select(); - - [Table(Name = "tb_topic22")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - - public partial class Song { - [Column(IsIdentity = true)] - public int Id { get; set; } - public DateTime? Create_time { get; set; } - public bool? Is_deleted { get; set; } - public string Title { get; set; } - public string Url { get; set; } - - public virtual ICollection Tags { get; set; } - } - public partial class Song_tag { - public int Song_id { get; set; } - public virtual Song Song { get; set; } - - public int Tag_id { get; set; } - public virtual Tag Tag { get; set; } - } - public partial class Tag { - [Column(IsIdentity = true)] - public int Id { get; set; } - public int? Parent_id { get; set; } - public virtual Tag Parent { get; set; } - - public decimal? Ddd { get; set; } - public string Name { get; set; } - - public virtual ICollection Songs { get; set; } - public virtual ICollection Tags { get; set; } - } - - [Fact] - public void AsSelect() { - //OneToOne、ManyToOne - var t0 = g.sqlite.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 - //FROM `Tag` a - //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` - //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` - //WHERE (a__Parent__Parent.`Name` = '粤语') - - //OneToMany - var t1 = g.sqlite.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); - //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` - //FROM `Tag` a - //WHERE (exists(SELECT 1 - // FROM `Tag` t - // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` - // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) - // limit 0,1)) - - //ManyToMany - var t2 = g.sqlite.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); - //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` - //FROM `Song` a - //WHERE(exists(SELECT 1 - // FROM `Song_tag` Mt_Ms - // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 - // FROM `Tag` t - // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) - // limit 0, 1)) - // limit 0, 1)) - } - - [Fact] - public void Lazy() { - var tags = g.sqlite.Select().Where(a => a.Parent.Name == "xxx") - .LeftJoin(a => a.Parent_id == a.Parent.Id) - .ToSql(); - - var songs = g.sqlite.Select().Limit(10).ToList(); - - - } - - [Fact] - public void ToDataTable() { - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); - - Assert.Equal(1, g.sqlite.Insert().AppendData(items.First()).ExecuteAffrows()); - Assert.Equal(10, g.sqlite.Insert().AppendData(items).ExecuteAffrows()); - - //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); - //Assert.Equal(9989, g.sqlite.Insert(items).ExecuteAffrows()); - - var dt1 = select.Limit(10).ToDataTable(); - var dt2 = select.Limit(10).ToDataTable("id, 111222"); - var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); - } - class TestDto { - public int id { get; set; } - public string name { get; set; } //这是join表的属性 - public int ParentId { get; set; } //这是join表的属性 - - public bool? testBool1 { get; set; } - public bool? testBool2 { get; set; } - } - class TestDtoLeftJoin { - [Column(IsPrimary = true)] - public int Guid { get; set; } - public bool? testBool1 { get; set; } - public bool? testBool2 { get; set; } - } - [Fact] - public void ToList() { - - g.sqlite.Delete().Where("1=1").ExecuteAffrows(); - var testlist = select.Limit(10).ToList(); - foreach(var testitem in testlist) { - var testdtolj = new TestDtoLeftJoin { Guid = testitem.TypeGuid, testBool1 = true }; - if (g.sqlite.Select().Where(a => a.Guid == testitem.TypeGuid).Any() == false) - g.sqlite.Insert(testdtolj).ExecuteAffrows(); - } - - var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto2 = select.Limit(10).ToList(a => new TestDto()); - var testDto3 = select.Limit(10).ToList(a => new TestDto { }); - var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); - - var testDto11 = select.LeftJoin((a,b) => b.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); - var testDto22 = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); - var testDto33 = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); - var testDto44 = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); - - g.sqlite.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); - var testGuidId5 = g.sqlite.Select().ToList(); - var testGuidId6 = g.sqlite.Select().ToList(a => a.id); - - var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); - var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); - } - class TestGuidIdToList { - public Guid id { get; set; } - public string title { get; set; } = Guid.NewGuid().ToString(); - } - [Fact] - public void ToOne() { - var testnotfind = select.Where("1=2").First(a => a.CreateTime); - Assert.Equal(default(DateTime), testnotfind); - } - [Fact] - public void ToSql() { - } - [Fact] - public void Any() { - var count = select.Where(a => 1 == 1).Count(); - Assert.False(select.Where(a => 1 == 2).Any()); - Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); - - var sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && - select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - //.Offset(a.Id) - .Any() - ).Any(c => c.Id == a.Id + 10) - ); - var sql2222Tolist = sql2222.ToList(); - - var collectionSelect = select.Where(a => - a.Type.Guid == a.TypeGuid && - a.Type.Parent.Id == a.Type.ParentId && - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) - ); - collectionSelect.ToList(); - } - [Fact] - public void Count() { - var count = select.Where(a => 1 == 1).Count(); - select.Where(a => 1 == 1).Count(out var count2); - Assert.Equal(count, count2); - Assert.Equal(0, select.Where(a => 1 == 2).Count()); - } - [Fact] - public void Master() { - Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); - } - [Fact] - public void From() { - var query2 = select.From((s, b) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - ); - var sql2 = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON a.\"TypeGuid\" = b.\"Guid\"", sql2); - query2.ToList(); - - var query3 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id) - ); - var sql3 = query3.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON a.\"TypeGuid\" = b.\"Guid\" LEFT JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql3); - query3.ToList(); - } - [Fact] - public void LeftJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\"", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TypeGuid\"", sql); - query.ToList(); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TypeGuid\" AND b.\"Name\" = 'xxx'", sql); - query.ToList(); - - query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); - query.ToList(); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql); - query.ToList(); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfo\" c ON c.\"Id\" = a__Type.\"ParentId\"", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON a.\"TypeGuid\" = b.\"Guid\" LEFT JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\""); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\"", sql); - query.ToList(); - - query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", sql); - query.ToList(); - } - [Fact] - public void InnerJoin() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\"", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); - query.ToList(); - - //���û�е������� - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TypeGuid\"", sql); - query.ToList(); - - query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TypeGuid\" AND b.\"Name\" = 'xxx'", sql); - query.ToList(); - - query = select.InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); - query.ToList(); - - //������� - query = select - .InnerJoin(a => a.Type.Guid == a.TypeGuid) - .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" INNER JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql); - query.ToList(); - - query = select - .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .InnerJoin((a, c) => c.Id == a.Type.ParentId); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" INNER JOIN \"TestTypeParentInfo\" c ON c.\"Id\" = a__Type.\"ParentId\"", sql); - query.ToList(); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .InnerJoin(a => b.ParentId == c.Id)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON a.\"TypeGuid\" = b.\"Guid\" INNER JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.InnerJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\""); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\"", sql); - query.ToList(); - - query = select.InnerJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", new { bname = "xxx" }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", sql); - query.ToList(); - - } - [Fact] - public void RightJoin() { - - } - [Fact] - public void Where() { - var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); - var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); - var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); - - var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.Where(a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Id\" = 10)", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE ((a.\"Id\" = 10 AND a.\"Id\" > 10 OR a.\"Clicks\" > 100))", sql); - query.ToList(); - - query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Id\" = 10) AND (a.\"Clicks\" > 100)", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" WHERE (a__Type.\"Name\" = 'typeTitle')", sql); - query.ToList(); - - query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" WHERE (a__Type.\"Name\" = 'typeTitle' AND a__Type.\"Guid\" = a.\"TypeGuid\")", sql); - query.ToList(); - - query = select.Where(a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Name\" = 'tparent')", sql); - query.ToList(); - - //���û�е������ԣ��򵥶������ - query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b WHERE (b.\"Guid\" = a.\"TypeGuid\" AND b.\"Name\" = 'typeTitle')", sql); - query.ToList(); - - query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b WHERE (b.\"Name\" = 'typeTitle' AND b.\"Guid\" = a.\"TypeGuid\")", sql); - query.ToList(); - - query = select.Where((a, b, c) => c.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeParentInfo\" c WHERE (c.\"Name\" = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .Where(a => a.Id == 10 && c.Name == "xxx") - .Where(a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b, \"TestTypeParentInfo\" c WHERE (a.\"Id\" = 10 AND c.\"Name\" = 'xxx') AND (b.\"ParentId\" = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.Where("a.\"Clicks\" > 100 and a.\"Id\" = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Clicks\" > 100 and a.\"Id\" = @id)", sql); - query.ToList(); - } - [Fact] - public void WhereIf() { - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.WhereIf(true, a => a.Id == 10); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Id\" = 10)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE ((a.\"Id\" = 10 AND a.\"Id\" > 10 OR a.\"Clicks\" > 100))", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Id\" = 10) AND (a.\"Clicks\" > 100)", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" WHERE (a__Type.\"Name\" = 'typeTitle')", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" WHERE (a__Type.\"Name\" = 'typeTitle' AND a__Type.\"Guid\" = a.\"TypeGuid\")", sql); - query.ToList(); - - query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Name\" = 'tparent')", sql); - query.ToList(); - - //����һ�� From ��Ķ������ - var query2 = select.From((s, b, c) => s - .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(true, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b, \"TestTypeParentInfo\" c WHERE (a.\"Id\" = 10 AND c.\"Name\" = 'xxx') AND (b.\"ParentId\" = 20)", sql); - query2.ToList(); - - //������϶����㲻�� - query = select.WhereIf(true, "a.\"Clicks\" > 100 and a.\"Id\" = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Clicks\" > 100 and a.\"Id\" = @id)", sql); - query.ToList(); - - // ==========================================WhereIf(false) - - //����е�������a.Type��a.Type.Parent ���ǵ������� - query = select.WhereIf(false, a => a.Id == 10); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); - query.First(); - - query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); - query.First(); - - query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); - query.First(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); - query.First(); - - query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); - query.First(); - - query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); - query.First(); - - //����һ�� From ��Ķ������ - query2 = select.From((s, b, c) => s - .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") - .WhereIf(false, a => b.ParentId == 20)); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b, \"TestTypeParentInfo\" c", sql); - query2.First(); - - //������϶����㲻�� - query = select.WhereIf(false, "a.\"Clicks\" > 100 and a.\"Id\" = @id", new { id = 10 }); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); - query.First(); - } - [Fact] - public void WhereExists() { - var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); - - sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - - //.Offset(a.Id) - - .Any() - ).Any() - ).ToList(); - } - [Fact] - public void GroupBy() { - var groupby = select.From((s, b, c) => s - .Where(a => a.Id == 1) - ) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()) - .Offset(10) - .Limit(2) - .ToList(a => new { - a.Key.tt2, - cou1 = a.Count(), - arg1 = a.Avg(a.Key.mod4), - ccc2 = a.Key.tt2 ?? "now()", - //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") - ccc3 = a.Max(a.Value.Item3.Id) - }); - - var testpid1 = g.sqlite.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); - g.sqlite.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); - - var aggsql1 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist1 = select - .GroupBy(a => a.Title) - .ToList(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToSql(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToList(b => new { - b.Key.Title, - b.Key.yyyy, - - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - - var aggsql3 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid), - sum3 = b.Sum(b.Value.Type.Parent.Id) - }); - } - [Fact] - public void ToAggregate() { - var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); - } - [Fact] - public void OrderBy() { - var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); - } - [Fact] - public void Skip_Offset() { - var sql = select.Offset(10).Limit(10).ToList(); - } - [Fact] - public void Take_Limit() { - var sql = select.Limit(10).ToList(); - } - [Fact] - public void Page() { - var sql1 = select.Page(1, 10).ToList(); - var sql2 = select.Page(2, 10).ToList(); - var sql3 = select.Page(3, 10).ToList(); - - var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); - var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); - var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); - } - [Fact] - public void Distinct() { - var t1 = select.Distinct().ToList(a => a.Title); - var t2 = select.Distinct().Limit(10).ToList(a => a.Title); - } - - [Fact] - public void Sum() { - } - [Fact] - public void Min() { - } - [Fact] - public void Max() { - } - [Fact] - public void Avg() { - } - [Fact] - public void As() { - } - - [Fact] - public void AsTable() { - - var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); - - var tenantId = 1; - var reposTopic = g.sqlite.GetGuidRepository(null, oldname => $"{oldname}_{tenantId}"); - var reposType = g.sqlite.GetGuidRepository(null, oldname => $"{oldname}_{tenantId}"); - - //reposTopic.Delete(Guid.Empty); - //reposTopic.Find(Guid.Empty); - //reposTopic.Update(new Topic { TypeGuid = 1 }); - var sql11 = reposTopic.Select - - .FromRepository(reposType) - .From((s,b,c) => s) - - .LeftJoin(a => a.TypeGuid == a.Type.Guid) - .ToSql(); - - - - Func tableRule = (type, oldname) => { - if (type == typeof(Topic)) return oldname + "AsTable1"; - else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; - return oldname + "AsTable"; - }; - - //����е�������a.Type��a.Type.Parent ���ǵ������� - var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); - var sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\"", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx'", sql); - - query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfoAsTable\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); - - //���û�е������� - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" b ON b.\"Guid\" = a.\"TypeGuid\"", sql); - - query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" b ON b.\"Guid\" = a.\"TypeGuid\" AND b.\"Name\" = 'xxx'", sql); - - query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfoAsTable\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); - - //������� - query = select - .LeftJoin(a => a.Type.Guid == a.TypeGuid) - .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfoAsTable\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql); - - query = select - .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) - .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfoAsTable\" c ON c.\"Id\" = a__Type.\"ParentId\"", sql); - - //���û�е�������b��c������ϵ - var query2 = select.From((s, b, c) => s - .LeftJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); - sql = query2.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" b ON a.\"TypeGuid\" = b.\"Guid\" LEFT JOIN \"TestTypeParentInfoAsTable\" c ON b.\"ParentId\" = c.\"Id\"", sql); - - //������϶����㲻�� - query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\"").AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\"", sql); - - query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", new { bname = "xxx" }).AsTable(tableRule); - sql = query.ToSql().Replace("\r\n", ""); - Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", sql); - } - - public class TestInclude_OneToManyModel1 { - [Column(IsIdentity = true)] - public int id { get; set; } - public virtual TestInclude_OneToManyModel2 model2 { get; set; } - - public string m1name { get; set; } - } - public class TestInclude_OneToManyModel2 { - [Column(IsPrimary = true)] - public int model2id { get; set; } - public virtual TestInclude_OneToManyModel1 model1 { get; set; } - - public string m2setting { get; set; } - - public List childs { get; set; } - } - public class TestInclude_OneToManyModel3 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model2111Idaaa { get; set; } - public string title { get; set; } - - public List childs2 { get; set; } - } - public class TestInclude_OneToManyModel4 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public int model3333Id333 { get; set; } - public string title444 { get; set; } - } - - [Fact] - public void Include_OneToMany() { - var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; - model1.id = (int)g.sqlite.Insert(model1).ExecuteIdentity(); - var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; - g.sqlite.Insert(model2).ExecuteAffrows(); - - var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; - model3_1.id = (int)g.sqlite.Insert(model3_1).ExecuteIdentity(); - var model3_2 =new TestInclude_OneToManyModel3{ model2111Idaaa = model1.id, title = "testmodel3__222" }; - model3_2.id = (int)g.sqlite.Insert(model3_2).ExecuteIdentity(); - var model3_3 = new TestInclude_OneToManyModel3{ model2111Idaaa = model1.id, title = "testmodel3__333" }; - model3_3.id = (int)g.sqlite.Insert(model3_2).ExecuteIdentity(); - - var model4s = new[] { - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, - new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } - }; - Assert.Equal(5, g.sqlite.Insert(model4s).ExecuteAffrows()); - - var t0 = g.sqlite.Select() - .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t1 = g.sqlite.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t2 = g.sqlite.Select() - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - - var t00 = g.sqlite.Select() - .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) - .Where(a => a.model2id <= model1.id) - .ToList(); - - var t11 = g.sqlite.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) - .Where(a => a.id <= model1.id) - .ToList(); - - var t22 = g.sqlite.Select() - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), - then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) - .Where(a => a.id <= model1.id) - .ToList(); - } - - public class TestInclude_OneToManyModel11 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2id { get; set; } - public string m3setting { get; set; } - public TestInclude_OneToManyModel22 model2 { get; set; } - public string m1name { get; set; } - } - - public class TestInclude_OneToManyModel22 { - [Column(IsIdentity = true)] - public int id { get; set; } - public string m2setting { get; set; } - public List childs { get; set; } - } - public class TestInclude_OneToManyModel33 { - [Column(IsIdentity = true)] - public int id { get; set; } - public int model2Id { get; set; } - public string title { get; set; } - public string setting { get; set; } - } - [Fact] - public void Include_OneToMany2() { - string setting = "x"; - var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; - model2.id = (int)g.sqlite.Insert(model2).ExecuteIdentity(); - - var model3s = new[] - { - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, - new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} - }; - Assert.Equal(3, g.sqlite.Insert(model3s).ExecuteAffrows()); - - var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; - model1.id = (int)g.sqlite.Insert(model1).ExecuteIdentity(); - - var t1 = g.sqlite.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - - var t11 = g.sqlite.Select() - .LeftJoin(a => a.model2id == a.model2.id) - .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) - .Where(a => a.id <= model1.id) - .ToList(true); - } - - [Fact] - public void Include_OneToChilds() { - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_中国" - }; - tag1.Id = (int)g.sqlite.Insert(tag1).ExecuteIdentity(); - var tag1_1 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_北京" - }; - tag1_1.Id = (int)g.sqlite.Insert(tag1_1).ExecuteIdentity(); - var tag1_2 = new Tag { - Parent_id = tag1.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_01_上海" - }; - tag1_2.Id = (int)g.sqlite.Insert(tag1_2).ExecuteIdentity(); - - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_美国" - }; - tag2.Id = (int)g.sqlite.Insert(tag2).ExecuteIdentity(); - var tag2_1 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_纽约" - }; - tag2_1.Id = (int)g.sqlite.Insert(tag2_1).ExecuteIdentity(); - var tag2_2 = new Tag { - Parent_id = tag2.Id, - Ddd = DateTime.Now.Second, - Name = "test_oneToChilds_02_华盛顿" - }; - tag2_2.Id = (int)g.sqlite.Insert(tag2_2).ExecuteIdentity(); - - var tags0 = g.sqlite.Select() - .Include(a => a.Parent) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags1 = g.sqlite.Select() - .IncludeMany(a => a.Tags) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags2 = g.sqlite.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags3 = g.sqlite.Select() - .IncludeMany(a => a.Tags, - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags11 = g.sqlite.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags22 = g.sqlite.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - - var tags33 = g.sqlite.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) - .Include(a => a.Parent) - .IncludeMany(a => a.Songs.Take(1)) - .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) - .ToList(); - } - - [Fact] - public void Include_ManyToMany() { - - var tag1 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_01_中国" - }; - tag1.Id = (int)g.sqlite.Insert(tag1).ExecuteIdentity(); - var tag2 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_02_美国" - }; - tag2.Id = (int)g.sqlite.Insert(tag2).ExecuteIdentity(); - var tag3 = new Tag { - Ddd = DateTime.Now.Second, - Name = "test_manytoMany_03_日本" - }; - tag3.Id = (int)g.sqlite.Insert(tag3).ExecuteIdentity(); - - var song1 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_01_我是中国人.mp3", - Url = "http://ww.baidu.com/" - }; - song1.Id = (int)g.sqlite.Insert(song1).ExecuteIdentity(); - var song2 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_02_爱你一万年.mp3", - Url = "http://ww.163.com/" - }; - song2.Id = (int)g.sqlite.Insert(song2).ExecuteIdentity(); - var song3 = new Song { - Create_time = DateTime.Now, - Title = "test_manytoMany_03_千年等一回.mp3", - Url = "http://ww.sina.com/" - }; - song3.Id = (int)g.sqlite.Insert(song3).ExecuteIdentity(); - - g.sqlite.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.sqlite.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.sqlite.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); - g.sqlite.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.sqlite.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); - g.sqlite.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); - - var songs1 = g.sqlite.Select() - .IncludeMany(a => a.Tags) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs1.Count); - Assert.Equal(2, songs1[0].Tags.Count); - Assert.Equal(1, songs1[1].Tags.Count); - Assert.Equal(3, songs1[2].Tags.Count); - - var songs2 = g.sqlite.Select() - .IncludeMany(a => a.Tags, - then => then.IncludeMany(t => t.Songs)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs2.Count); - Assert.Equal(2, songs2[0].Tags.Count); - Assert.Equal(1, songs2[1].Tags.Count); - Assert.Equal(3, songs2[2].Tags.Count); - - var tags3 = g.sqlite.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - - - var songs11 = g.sqlite.Select() - .IncludeMany(a => a.Tags.Take(1)) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs11.Count); - Assert.Equal(1, songs11[0].Tags.Count); - Assert.Equal(1, songs11[1].Tags.Count); - Assert.Equal(1, songs11[2].Tags.Count); - - var songs22 = g.sqlite.Select() - .IncludeMany(a => a.Tags.Take(1), - then => then.IncludeMany(t => t.Songs.Take(1))) - .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) - .ToList(); - Assert.Equal(3, songs22.Count); - Assert.Equal(1, songs22[0].Tags.Count); - Assert.Equal(1, songs22[1].Tags.Count); - Assert.Equal(1, songs22[2].Tags.Count); - - var tags33 = g.sqlite.Select() - .Include(a => a.Tag.Parent) - .IncludeMany(a => a.Tag.Songs.Take(1)) - .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) - .ToList(true); - } - } +namespace FreeSql.Tests.Sqlite +{ + public class SqliteSelectTest + { + + ISelect select => g.sqlite.Select(); + + [Table(Name = "tb_topic22")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + + public partial class Song + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public DateTime? Create_time { get; set; } + public bool? Is_deleted { get; set; } + public string Title { get; set; } + public string Url { get; set; } + + public virtual ICollection Tags { get; set; } + } + public partial class Song_tag + { + public int Song_id { get; set; } + public virtual Song Song { get; set; } + + public int Tag_id { get; set; } + public virtual Tag Tag { get; set; } + } + public partial class Tag + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public int? Parent_id { get; set; } + public virtual Tag Parent { get; set; } + + public decimal? Ddd { get; set; } + public string Name { get; set; } + + public virtual ICollection Songs { get; set; } + public virtual ICollection Tags { get; set; } + } + + [Fact] + public void AsSelect() + { + //OneToOne、ManyToOne + var t0 = g.sqlite.Select().Where(a => a.Parent.Parent.Name == "粤语").ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a__Parent.`Id` as3, a__Parent.`Parent_id` as4, a__Parent.`Ddd`, a__Parent.`Name`, a.`Ddd` as7, a.`Name` as8 + //FROM `Tag` a + //LEFT JOIN `Tag` a__Parent ON a__Parent.`Id` = a.`Parent_id` + //LEFT JOIN `Tag` a__Parent__Parent ON a__Parent__Parent.`Id` = a__Parent.`Parent_id` + //WHERE (a__Parent__Parent.`Name` = '粤语') + + //OneToMany + var t1 = g.sqlite.Select().Where(a => a.Tags.AsSelect().Any(t => t.Parent.Id == 10)).ToSql(); + //SELECT a.`Id`, a.`Parent_id`, a.`Ddd`, a.`Name` + //FROM `Tag` a + //WHERE (exists(SELECT 1 + // FROM `Tag` t + // LEFT JOIN `Tag` t__Parent ON t__Parent.`Id` = t.`Parent_id` + // WHERE (t__Parent.`Id` = 10) AND (t.`Parent_id` = a.`Id`) + // limit 0,1)) + + //ManyToMany + var t2 = g.sqlite.Select().Where(s => s.Tags.AsSelect().Any(t => t.Name == "国语")).ToSql(); + //SELECT a.`Id`, a.`Create_time`, a.`Is_deleted`, a.`Title`, a.`Url` + //FROM `Song` a + //WHERE(exists(SELECT 1 + // FROM `Song_tag` Mt_Ms + // WHERE(Mt_Ms.`Song_id` = a.`Id`) AND(exists(SELECT 1 + // FROM `Tag` t + // WHERE(t.`Name` = '国语') AND(t.`Id` = Mt_Ms.`Tag_id`) + // limit 0, 1)) + // limit 0, 1)) + } + + [Fact] + public void Lazy() + { + var tags = g.sqlite.Select().Where(a => a.Parent.Name == "xxx") + .LeftJoin(a => a.Parent_id == a.Parent.Id) + .ToSql(); + + var songs = g.sqlite.Select().Limit(10).ToList(); + + + } + + [Fact] + public void ToDataTable() + { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100, CreateTime = DateTime.Now }); + + Assert.Equal(1, g.sqlite.Insert().AppendData(items.First()).ExecuteAffrows()); + Assert.Equal(10, g.sqlite.Insert().AppendData(items).ExecuteAffrows()); + + //items = Enumerable.Range(0, 9989).Select(a => new Topic { Title = "newtitle" + a, CreateTime = DateTime.Now }).ToList(); + //Assert.Equal(9989, g.sqlite.Insert(items).ExecuteAffrows()); + + var dt1 = select.Limit(10).ToDataTable(); + var dt2 = select.Limit(10).ToDataTable("id, 111222"); + var dt3 = select.Limit(10).ToDataTable(a => new { a.Id, a.Type.Name, now = DateTime.Now }); + } + class TestDto + { + public int id { get; set; } + public string name { get; set; } //这是join表的属性 + public int ParentId { get; set; } //这是join表的属性 + + public bool? testBool1 { get; set; } + public bool? testBool2 { get; set; } + } + class TestDtoLeftJoin + { + [Column(IsPrimary = true)] + public int Guid { get; set; } + public bool? testBool1 { get; set; } + public bool? testBool2 { get; set; } + } + [Fact] + public void ToList() + { + + g.sqlite.Delete().Where("1=1").ExecuteAffrows(); + var testlist = select.Limit(10).ToList(); + foreach (var testitem in testlist) + { + var testdtolj = new TestDtoLeftJoin { Guid = testitem.TypeGuid, testBool1 = true }; + if (g.sqlite.Select().Where(a => a.Guid == testitem.TypeGuid).Any() == false) + g.sqlite.Insert(testdtolj).ExecuteAffrows(); + } + + var testDto1 = select.Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto2 = select.Limit(10).ToList(a => new TestDto()); + var testDto3 = select.Limit(10).ToList(a => new TestDto { }); + var testDto4 = select.Limit(10).ToList(a => new TestDto() { }); + + var testDto11 = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { id = a.Id, name = a.Title }); + var testDto22 = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto()); + var testDto33 = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto { }); + var testDto44 = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).Limit(10).ToList(a => new TestDto() { }); + + g.sqlite.Insert().AppendData(new TestGuidIdToList()).ExecuteAffrows(); + var testGuidId5 = g.sqlite.Select().ToList(); + var testGuidId6 = g.sqlite.Select().ToList(a => a.id); + + var t11 = select.Where(a => a.Type.Name.Length > 0).ToList(true); + var t21 = select.Where(a => a.Type.Parent.Name.Length > 0).ToList(true); + } + class TestGuidIdToList + { + public Guid id { get; set; } + public string title { get; set; } = Guid.NewGuid().ToString(); + } + [Fact] + public void ToOne() + { + var testnotfind = select.Where("1=2").First(a => a.CreateTime); + Assert.Equal(default(DateTime), testnotfind); + } + [Fact] + public void ToSql() + { + } + [Fact] + public void Any() + { + var count = select.Where(a => 1 == 1).Count(); + Assert.False(select.Where(a => 1 == 2).Any()); + Assert.Equal(count > 0, select.Where(a => 1 == 1).Any()); + + var sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && + select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + //.Offset(a.Id) + .Any() + ).Any(c => c.Id == a.Id + 10) + ); + var sql2222Tolist = sql2222.ToList(); + + var collectionSelect = select.Where(a => + a.Type.Guid == a.TypeGuid && + a.Type.Parent.Id == a.Type.ParentId && + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any(b => b.ParentId == a.Type.Parent.Id) + ); + collectionSelect.ToList(); + } + [Fact] + public void Count() + { + var count = select.Where(a => 1 == 1).Count(); + select.Where(a => 1 == 1).Count(out var count2); + Assert.Equal(count, count2); + Assert.Equal(0, select.Where(a => 1 == 2).Count()); + } + [Fact] + public void Master() + { + Assert.StartsWith(" SELECT", select.Master().Where(a => 1 == 1).ToSql()); + } + [Fact] + public void From() + { + var query2 = select.From((s, b) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + ); + var sql2 = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON a.\"TypeGuid\" = b.\"Guid\"", sql2); + query2.ToList(); + + var query3 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id) + ); + var sql3 = query3.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON a.\"TypeGuid\" = b.\"Guid\" LEFT JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql3); + query3.ToList(); + } + [Fact] + public void LeftJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\"", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TypeGuid\"", sql); + query.ToList(); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TypeGuid\" AND b.\"Name\" = 'xxx'", sql); + query.ToList(); + + query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); + query.ToList(); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql); + query.ToList(); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfo\" c ON c.\"Id\" = a__Type.\"ParentId\"", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b ON a.\"TypeGuid\" = b.\"Guid\" LEFT JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\""); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\"", sql); + query.ToList(); + + query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", sql); + query.ToList(); + } + [Fact] + public void InnerJoin() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\"", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); + query.ToList(); + + //���û�е������� + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TypeGuid\"", sql); + query.ToList(); + + query = select.InnerJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON b.\"Guid\" = a.\"TypeGuid\" AND b.\"Name\" = 'xxx'", sql); + query.ToList(); + + query = select.InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); + query.ToList(); + + //������� + query = select + .InnerJoin(a => a.Type.Guid == a.TypeGuid) + .InnerJoin(a => a.Type.Parent.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" INNER JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql); + query.ToList(); + + query = select + .InnerJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .InnerJoin((a, c) => c.Id == a.Type.ParentId); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" INNER JOIN \"TestTypeParentInfo\" c ON c.\"Id\" = a__Type.\"ParentId\"", sql); + query.ToList(); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .InnerJoin(a => b.ParentId == c.Id)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b ON a.\"TypeGuid\" = b.\"Guid\" INNER JOIN \"TestTypeParentInfo\" c ON b.\"ParentId\" = c.\"Id\"", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.InnerJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\""); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\"", sql); + query.ToList(); + + query = select.InnerJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", new { bname = "xxx" }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a INNER JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", sql); + query.ToList(); + + } + [Fact] + public void RightJoin() + { + + } + [Fact] + public void Where() + { + var sqltmp1 = select.Where(a => a.Id == 0 && (a.Title == "x" || a.Title == "y") && a.Clicks == 1).ToSql(); + var sqltmp2 = select.Where(a => a.Id.Equals(true) && (a.Title.Equals("x") || a.Title.Equals("y")) && a.Clicks.Equals(1)).ToSql(); + var sqltmp3 = select.Where(a => a.Id == 0).Where(a => ((a.Title == "x" && a.Title == "z") || a.Title == "y")).ToSql(); + + var sqltmp4 = select.Where(a => (a.Id - 10) / 2 > 0).ToSql(); + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.Where(a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Id\" = 10)", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE ((a.\"Id\" = 10 AND a.\"Id\" > 10 OR a.\"Clicks\" > 100))", sql); + query.ToList(); + + query = select.Where(a => a.Id == 10).Where(a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Id\" = 10) AND (a.\"Clicks\" > 100)", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" WHERE (a__Type.\"Name\" = 'typeTitle')", sql); + query.ToList(); + + query = select.Where(a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" WHERE (a__Type.\"Name\" = 'typeTitle' AND a__Type.\"Guid\" = a.\"TypeGuid\")", sql); + query.ToList(); + + query = select.Where(a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Name\" = 'tparent')", sql); + query.ToList(); + + //���û�е������ԣ��򵥶������ + query = select.Where((a, b) => b.Guid == a.TypeGuid && b.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b WHERE (b.\"Guid\" = a.\"TypeGuid\" AND b.\"Name\" = 'typeTitle')", sql); + query.ToList(); + + query = select.Where((a, b) => b.Name == "typeTitle" && b.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b WHERE (b.\"Name\" = 'typeTitle' AND b.\"Guid\" = a.\"TypeGuid\")", sql); + query.ToList(); + + query = select.Where((a, b, c) => c.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeParentInfo\" c WHERE (c.\"Name\" = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .Where(a => a.Id == 10 && c.Name == "xxx") + .Where(a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b, \"TestTypeParentInfo\" c WHERE (a.\"Id\" = 10 AND c.\"Name\" = 'xxx') AND (b.\"ParentId\" = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.Where("a.\"Clicks\" > 100 and a.\"Id\" = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Clicks\" > 100 and a.\"Id\" = @id)", sql); + query.ToList(); + } + [Fact] + public void WhereIf() + { + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.WhereIf(true, a => a.Id == 10); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Id\" = 10)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE ((a.\"Id\" = 10 AND a.\"Id\" > 10 OR a.\"Clicks\" > 100))", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Id == 10).WhereIf(true, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Id\" = 10) AND (a.\"Clicks\" > 100)", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" WHERE (a__Type.\"Name\" = 'typeTitle')", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" WHERE (a__Type.\"Name\" = 'typeTitle' AND a__Type.\"Guid\" = a.\"TypeGuid\")", sql); + query.ToList(); + + query = select.WhereIf(true, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a LEFT JOIN \"TestTypeInfo\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfo\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Name\" = 'tparent')", sql); + query.ToList(); + + //����һ�� From ��Ķ������ + var query2 = select.From((s, b, c) => s + .WhereIf(true, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(true, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b, \"TestTypeParentInfo\" c WHERE (a.\"Id\" = 10 AND c.\"Name\" = 'xxx') AND (b.\"ParentId\" = 20)", sql); + query2.ToList(); + + //������϶����㲻�� + query = select.WhereIf(true, "a.\"Clicks\" > 100 and a.\"Id\" = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a WHERE (a.\"Clicks\" > 100 and a.\"Id\" = @id)", sql); + query.ToList(); + + // ==========================================WhereIf(false) + + //����е�������a.Type��a.Type.Parent ���ǵ������� + query = select.WhereIf(false, a => a.Id == 10); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); + query.First(); + + query = select.WhereIf(false, a => a.Id == 10 && a.Id > 10 || a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); + query.First(); + + query = select.WhereIf(false, a => a.Id == 10).WhereIf(false, a => a.Clicks > 100); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); + query.First(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); + query.First(); + + query = select.WhereIf(false, a => a.Type.Name == "typeTitle" && a.Type.Guid == a.TypeGuid); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); + query.First(); + + query = select.WhereIf(false, a => a.Type.Parent.Name == "tparent"); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); + query.First(); + + //����һ�� From ��Ķ������ + query2 = select.From((s, b, c) => s + .WhereIf(false, a => a.Id == 10 && c.Name == "xxx") + .WhereIf(false, a => b.ParentId == 20)); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a, \"TestTypeInfo\" b, \"TestTypeParentInfo\" c", sql); + query2.First(); + + //������϶����㲻�� + query = select.WhereIf(false, "a.\"Clicks\" > 100 and a.\"Id\" = @id", new { id = 10 }); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22\" a", sql); + query.First(); + } + [Fact] + public void WhereExists() + { + var sql2222 = select.Where(a => select.Where(b => b.Id == a.Id).Any()).ToList(); + + sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + + //.Offset(a.Id) + + .Any() + ).Any() + ).ToList(); + } + [Fact] + public void GroupBy() + { + var groupby = select.From((s, b, c) => s + .Where(a => a.Id == 1) + ) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()) + .Offset(10) + .Limit(2) + .ToList(a => new + { + a.Key.tt2, + cou1 = a.Count(), + arg1 = a.Avg(a.Key.mod4), + ccc2 = a.Key.tt2 ?? "now()", + //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") + ccc3 = a.Max(a.Value.Item3.Id) + }); + + var testpid1 = g.sqlite.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); + g.sqlite.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); + + var aggsql1 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist1 = select + .GroupBy(a => a.Title) + .ToList(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToSql(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToList(b => new + { + b.Key.Title, + b.Key.yyyy, + + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + + var aggsql3 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid), + sum3 = b.Sum(b.Value.Type.Parent.Id) + }); + } + [Fact] + public void ToAggregate() + { + var sql = select.ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); + } + [Fact] + public void OrderBy() + { + var sql = select.OrderBy(a => new Random().NextDouble()).ToList(); + } + [Fact] + public void Skip_Offset() + { + var sql = select.Offset(10).Limit(10).ToList(); + } + [Fact] + public void Take_Limit() + { + var sql = select.Limit(10).ToList(); + } + [Fact] + public void Page() + { + var sql1 = select.Page(1, 10).ToList(); + var sql2 = select.Page(2, 10).ToList(); + var sql3 = select.Page(3, 10).ToList(); + + var sql11 = select.OrderBy(a => new Random().NextDouble()).Page(1, 10).ToList(); + var sql22 = select.OrderBy(a => new Random().NextDouble()).Page(2, 10).ToList(); + var sql33 = select.OrderBy(a => new Random().NextDouble()).Page(3, 10).ToList(); + } + [Fact] + public void Distinct() + { + var t1 = select.Distinct().ToList(a => a.Title); + var t2 = select.Distinct().Limit(10).ToList(a => a.Title); + } + + [Fact] + public void Sum() + { + } + [Fact] + public void Min() + { + } + [Fact] + public void Max() + { + } + [Fact] + public void Avg() + { + } + [Fact] + public void As() + { + } + + [Fact] + public void AsTable() + { + + var listt = select.AsTable((a, b) => "(select * from tb_topic where clicks > 10)").Page(1, 10).ToList(); + + var tenantId = 1; + var reposTopic = g.sqlite.GetGuidRepository(null, oldname => $"{oldname}_{tenantId}"); + var reposType = g.sqlite.GetGuidRepository(null, oldname => $"{oldname}_{tenantId}"); + + //reposTopic.Delete(Guid.Empty); + //reposTopic.Find(Guid.Empty); + //reposTopic.Update(new Topic { TypeGuid = 1 }); + var sql11 = reposTopic.Select + + .FromRepository(reposType) + .From((s, b, c) => s) + + .LeftJoin(a => a.TypeGuid == a.Type.Guid) + .ToSql(); + + + + Func tableRule = (type, oldname) => + { + if (type == typeof(Topic)) return oldname + "AsTable1"; + else if (type == typeof(TestTypeInfo)) return oldname + "AsTable2"; + return oldname + "AsTable"; + }; + + //����е�������a.Type��a.Type.Parent ���ǵ������� + var query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).AsTable(tableRule); + var sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\"", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx'", sql); + + query = select.LeftJoin(a => a.Type.Guid == a.TypeGuid && a.Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfoAsTable\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); + + //���û�е������� + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" b ON b.\"Guid\" = a.\"TypeGuid\"", sql); + + query = select.LeftJoin((a, b) => b.Guid == a.TypeGuid && b.Name == "xxx").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" b ON b.\"Guid\" = a.\"TypeGuid\" AND b.\"Name\" = 'xxx'", sql); + + query = select.LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid && a__Type.Name == "xxx").Where(a => a.Type.Parent.Id == 10).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" AND a__Type.\"Name\" = 'xxx' LEFT JOIN \"TestTypeParentInfoAsTable\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\" WHERE (a__Type__Parent.\"Id\" = 10)", sql); + + //������� + query = select + .LeftJoin(a => a.Type.Guid == a.TypeGuid) + .LeftJoin(a => a.Type.Parent.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfoAsTable\" a__Type__Parent ON a__Type__Parent.\"Id\" = a__Type.\"ParentId\"", sql); + + query = select + .LeftJoin((a, a__Type) => a__Type.Guid == a.TypeGuid) + .LeftJoin((a, c) => c.Id == a.Type.ParentId).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a__Type.\"Guid\", a__Type.\"ParentId\", a__Type.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" a__Type ON a__Type.\"Guid\" = a.\"TypeGuid\" LEFT JOIN \"TestTypeParentInfoAsTable\" c ON c.\"Id\" = a__Type.\"ParentId\"", sql); + + //���û�е�������b��c������ϵ + var query2 = select.From((s, b, c) => s + .LeftJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => b.ParentId == c.Id)).AsTable(tableRule); + sql = query2.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", b.\"Guid\", b.\"ParentId\", b.\"Name\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfoAsTable2\" b ON a.\"TypeGuid\" = b.\"Guid\" LEFT JOIN \"TestTypeParentInfoAsTable\" c ON b.\"ParentId\" = c.\"Id\"", sql); + + //������϶����㲻�� + query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\"").AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\"", sql); + + query = select.LeftJoin("\"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", new { bname = "xxx" }).AsTable(tableRule); + sql = query.ToSql().Replace("\r\n", ""); + Assert.Equal("SELECT a.\"Id\", a.\"Clicks\", a.\"TypeGuid\", a.\"Title\", a.\"CreateTime\" FROM \"tb_topic22AsTable1\" a LEFT JOIN \"TestTypeInfo\" b on b.\"Guid\" = a.\"TypeGuid\" and b.\"Name\" = @bname", sql); + } + + public class TestInclude_OneToManyModel1 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public virtual TestInclude_OneToManyModel2 model2 { get; set; } + + public string m1name { get; set; } + } + public class TestInclude_OneToManyModel2 + { + [Column(IsPrimary = true)] + public int model2id { get; set; } + public virtual TestInclude_OneToManyModel1 model1 { get; set; } + + public string m2setting { get; set; } + + public List childs { get; set; } + } + public class TestInclude_OneToManyModel3 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model2111Idaaa { get; set; } + public string title { get; set; } + + public List childs2 { get; set; } + } + public class TestInclude_OneToManyModel4 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public int model3333Id333 { get; set; } + public string title444 { get; set; } + } + + [Fact] + public void Include_OneToMany() + { + var model1 = new TestInclude_OneToManyModel1 { m1name = DateTime.Now.Second.ToString() }; + model1.id = (int)g.sqlite.Insert(model1).ExecuteIdentity(); + var model2 = new TestInclude_OneToManyModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; + g.sqlite.Insert(model2).ExecuteAffrows(); + + var model3_1 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; + model3_1.id = (int)g.sqlite.Insert(model3_1).ExecuteIdentity(); + var model3_2 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; + model3_2.id = (int)g.sqlite.Insert(model3_2).ExecuteIdentity(); + var model3_3 = new TestInclude_OneToManyModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; + model3_3.id = (int)g.sqlite.Insert(model3_2).ExecuteIdentity(); + + var model4s = new[] { + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, + new TestInclude_OneToManyModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } + }; + Assert.Equal(5, g.sqlite.Insert(model4s).ExecuteAffrows()); + + var t0 = g.sqlite.Select() + .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t1 = g.sqlite.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t2 = g.sqlite.Select() + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + + var t00 = g.sqlite.Select() + .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) + .Where(a => a.model2id <= model1.id) + .ToList(); + + var t11 = g.sqlite.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) + .Where(a => a.id <= model1.id) + .ToList(); + + var t22 = g.sqlite.Select() + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), + then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) + .Where(a => a.id <= model1.id) + .ToList(); + } + + public class TestInclude_OneToManyModel11 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2id { get; set; } + public string m3setting { get; set; } + public TestInclude_OneToManyModel22 model2 { get; set; } + public string m1name { get; set; } + } + + public class TestInclude_OneToManyModel22 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public string m2setting { get; set; } + public List childs { get; set; } + } + public class TestInclude_OneToManyModel33 + { + [Column(IsIdentity = true)] + public int id { get; set; } + public int model2Id { get; set; } + public string title { get; set; } + public string setting { get; set; } + } + [Fact] + public void Include_OneToMany2() + { + string setting = "x"; + var model2 = new TestInclude_OneToManyModel22 { m2setting = DateTime.Now.Second.ToString() }; + model2.id = (int)g.sqlite.Insert(model2).ExecuteIdentity(); + + var model3s = new[] + { + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__111", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__222", setting = setting}, + new TestInclude_OneToManyModel33 {model2Id = model2.id, title = "testmodel3__333", setting = setting} + }; + Assert.Equal(3, g.sqlite.Insert(model3s).ExecuteAffrows()); + + var model1 = new TestInclude_OneToManyModel11 { m1name = DateTime.Now.Second.ToString(), model2id = model2.id, m3setting = setting }; + model1.id = (int)g.sqlite.Insert(model1).ExecuteIdentity(); + + var t1 = g.sqlite.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + + var t11 = g.sqlite.Select() + .LeftJoin(a => a.model2id == a.model2.id) + .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2Id == a.model2.id && m3.setting == a.m3setting)) + .Where(a => a.id <= model1.id) + .ToList(true); + } + + [Fact] + public void Include_OneToChilds() + { + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_中国" + }; + tag1.Id = (int)g.sqlite.Insert(tag1).ExecuteIdentity(); + var tag1_1 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_北京" + }; + tag1_1.Id = (int)g.sqlite.Insert(tag1_1).ExecuteIdentity(); + var tag1_2 = new Tag + { + Parent_id = tag1.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_01_上海" + }; + tag1_2.Id = (int)g.sqlite.Insert(tag1_2).ExecuteIdentity(); + + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_美国" + }; + tag2.Id = (int)g.sqlite.Insert(tag2).ExecuteIdentity(); + var tag2_1 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_纽约" + }; + tag2_1.Id = (int)g.sqlite.Insert(tag2_1).ExecuteIdentity(); + var tag2_2 = new Tag + { + Parent_id = tag2.Id, + Ddd = DateTime.Now.Second, + Name = "test_oneToChilds_02_华盛顿" + }; + tag2_2.Id = (int)g.sqlite.Insert(tag2_2).ExecuteIdentity(); + + var tags0 = g.sqlite.Select() + .Include(a => a.Parent) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags1 = g.sqlite.Select() + .IncludeMany(a => a.Tags) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags2 = g.sqlite.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags3 = g.sqlite.Select() + .IncludeMany(a => a.Tags, + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs).IncludeMany(a => a.Tags)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags11 = g.sqlite.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags22 = g.sqlite.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + + var tags33 = g.sqlite.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.Include(a => a.Parent).IncludeMany(a => a.Songs.Take(1)).IncludeMany(a => a.Tags.Take(1))) + .Include(a => a.Parent) + .IncludeMany(a => a.Songs.Take(1)) + .Where(a => a.Id == tag1.Id || a.Id == tag2.Id) + .ToList(); + } + + [Fact] + public void Include_ManyToMany() + { + + var tag1 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_01_中国" + }; + tag1.Id = (int)g.sqlite.Insert(tag1).ExecuteIdentity(); + var tag2 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_02_美国" + }; + tag2.Id = (int)g.sqlite.Insert(tag2).ExecuteIdentity(); + var tag3 = new Tag + { + Ddd = DateTime.Now.Second, + Name = "test_manytoMany_03_日本" + }; + tag3.Id = (int)g.sqlite.Insert(tag3).ExecuteIdentity(); + + var song1 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_01_我是中国人.mp3", + Url = "http://ww.baidu.com/" + }; + song1.Id = (int)g.sqlite.Insert(song1).ExecuteIdentity(); + var song2 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_02_爱你一万年.mp3", + Url = "http://ww.163.com/" + }; + song2.Id = (int)g.sqlite.Insert(song2).ExecuteIdentity(); + var song3 = new Song + { + Create_time = DateTime.Now, + Title = "test_manytoMany_03_千年等一回.mp3", + Url = "http://ww.sina.com/" + }; + song3.Id = (int)g.sqlite.Insert(song3).ExecuteIdentity(); + + g.sqlite.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.sqlite.Insert(new Song_tag { Song_id = song2.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.sqlite.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag1.Id }).ExecuteAffrows(); + g.sqlite.Insert(new Song_tag { Song_id = song1.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.sqlite.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag2.Id }).ExecuteAffrows(); + g.sqlite.Insert(new Song_tag { Song_id = song3.Id, Tag_id = tag3.Id }).ExecuteAffrows(); + + var songs1 = g.sqlite.Select() + .IncludeMany(a => a.Tags) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs1.Count); + Assert.Equal(2, songs1[0].Tags.Count); + Assert.Equal(1, songs1[1].Tags.Count); + Assert.Equal(3, songs1[2].Tags.Count); + + var songs2 = g.sqlite.Select() + .IncludeMany(a => a.Tags, + then => then.IncludeMany(t => t.Songs)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs2.Count); + Assert.Equal(2, songs2[0].Tags.Count); + Assert.Equal(1, songs2[1].Tags.Count); + Assert.Equal(3, songs2[2].Tags.Count); + + var tags3 = g.sqlite.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + + + var songs11 = g.sqlite.Select() + .IncludeMany(a => a.Tags.Take(1)) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs11.Count); + Assert.Equal(1, songs11[0].Tags.Count); + Assert.Equal(1, songs11[1].Tags.Count); + Assert.Equal(1, songs11[2].Tags.Count); + + var songs22 = g.sqlite.Select() + .IncludeMany(a => a.Tags.Take(1), + then => then.IncludeMany(t => t.Songs.Take(1))) + .Where(a => a.Id == song1.Id || a.Id == song2.Id || a.Id == song3.Id) + .ToList(); + Assert.Equal(3, songs22.Count); + Assert.Equal(1, songs22[0].Tags.Count); + Assert.Equal(1, songs22[1].Tags.Count); + Assert.Equal(1, songs22[2].Tags.Count); + + var tags33 = g.sqlite.Select() + .Include(a => a.Tag.Parent) + .IncludeMany(a => a.Tag.Songs.Take(1)) + .Where(a => a.Tag.Id == tag1.Id || a.Tag.Id == tag2.Id) + .ToList(true); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteUpdateTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteUpdateTest.cs index 05d00ce3..e6ac094e 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteUpdateTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/Curd/SqliteUpdateTest.cs @@ -3,129 +3,143 @@ using System; using System.Collections.Generic; using Xunit; -namespace FreeSql.Tests.Sqlite { - public class SqliteUpdateTest { - IUpdate update => g.sqlite.Update(); +namespace FreeSql.Tests.Sqlite +{ + public class SqliteUpdateTest + { + IUpdate update => g.sqlite.Update(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int? Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int? Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void Dywhere() { - Assert.Null(g.sqlite.Update().ToSql()); - Assert.Equal("UPDATE \"tb_topic\" SET title='test' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); - Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); - Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); - } + [Fact] + public void Dywhere() + { + Assert.Null(g.sqlite.Update().ToSql()); + Assert.Equal("UPDATE \"tb_topic\" SET title='test' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite.Update(new[] { 1, 2 }).SetRaw("title='test'").ToSql()); + Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").ToSql()); + Assert.Equal("UPDATE \"tb_topic\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite.Update(new { id = 1 }).SetRaw("title='test1'").ToSql()); + } - [Fact] - public void SetSource() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => a.TypeGuid).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = @p_0, \"Title\" = @p_1, \"CreateTime\" = @p_2 WHERE (\"Id\" = 1)", sql); + [Fact] + public void SetSource() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => a.TypeGuid).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = @p_0, \"Title\" = @p_1, \"CreateTime\" = @p_2 WHERE (\"Id\" = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.SetSource(items).IgnoreColumns(a => a.TypeGuid).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = CASE \"Id\" WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, \"Title\" = CASE \"Id\" WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, \"CreateTime\" = CASE \"Id\" WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).IgnoreColumns(a => a.TypeGuid).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = CASE \"Id\" WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END, \"Title\" = CASE \"Id\" WHEN 1 THEN @p_10 WHEN 2 THEN @p_11 WHEN 3 THEN @p_12 WHEN 4 THEN @p_13 WHEN 5 THEN @p_14 WHEN 6 THEN @p_15 WHEN 7 THEN @p_16 WHEN 8 THEN @p_17 WHEN 9 THEN @p_18 WHEN 10 THEN @p_19 END, \"CreateTime\" = CASE \"Id\" WHEN 1 THEN @p_20 WHEN 2 THEN @p_21 WHEN 3 THEN @p_22 WHEN 4 THEN @p_23 WHEN 5 THEN @p_24 WHEN 6 THEN @p_25 WHEN 7 THEN @p_26 WHEN 8 THEN @p_27 WHEN 9 THEN @p_28 WHEN 10 THEN @p_29 END WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime, a.TypeGuid }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = CASE \"Id\" WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + sql = update.SetSource(items).IgnoreColumns(a => new { a.Clicks, a.CreateTime, a.TypeGuid }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = CASE \"Id\" WHEN 1 THEN @p_0 WHEN 2 THEN @p_1 WHEN 3 THEN @p_2 WHEN 4 THEN @p_3 WHEN 5 THEN @p_4 WHEN 6 THEN @p_5 WHEN 7 THEN @p_6 WHEN 8 THEN @p_7 WHEN 9 THEN @p_8 WHEN 10 THEN @p_9 END WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - sql = update.SetSource(items).IgnoreColumns(a => a.TypeGuid).Set(a => a.CreateTime, new DateTime(2020,1,1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"CreateTime\" = @p_0 WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void IgnoreColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime, a.TypeGuid }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = @p_0 WHERE (\"Id\" = 1)", sql); - } - [Fact] - public void UpdateColumns() { - var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = @p_0 WHERE (\"Id\" = 1)", sql); - } - [Fact] - public void Set() { - var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = @p_0 WHERE (\"Id\" = 1)", sql); + sql = update.SetSource(items).IgnoreColumns(a => a.TypeGuid).Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"CreateTime\" = @p_0 WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void IgnoreColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).IgnoreColumns(a => new { a.Clicks, a.CreateTime, a.TypeGuid }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = @p_0 WHERE (\"Id\" = 1)", sql); + } + [Fact] + public void UpdateColumns() + { + var sql = update.SetSource(new Topic { Id = 1, Title = "newtitle" }).UpdateColumns(a => a.Title).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = @p_0 WHERE (\"Id\" = 1)", sql); + } + [Fact] + public void Set() + { + var sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = @p_0 WHERE (\"Id\" = 1)", sql); - sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = @p_0, \"CreateTime\" = @p_1 WHERE (\"Id\" = 1)", sql); + sql = update.Where(a => a.Id == 1).Set(a => a.Title, "newtitle").Set(a => a.CreateTime, new DateTime(2020, 1, 1)).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Title\" = @p_0, \"CreateTime\" = @p_1 WHERE (\"Id\" = 1)", sql); - sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = ifnull(\"Clicks\", 0) * 10 / 1 WHERE (\"Id\" = 1)", sql); + sql = update.Set(a => a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = ifnull(\"Clicks\", 0) * 10 / 1 WHERE (\"Id\" = 1)", sql); - sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Id\" = (\"Id\" - 10) WHERE (\"Id\" = 1)", sql); + sql = update.Set(a => a.Id - 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Id\" = (\"Id\" - 10) WHERE (\"Id\" = 1)", sql); - int incrv = 10; - sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = ifnull(\"Clicks\", 0) * 10 / 1 WHERE (\"Id\" = 1)", sql); + int incrv = 10; + sql = update.Set(a => a.Clicks * incrv / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = ifnull(\"Clicks\", 0) * 10 / 1 WHERE (\"Id\" = 1)", sql); - sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Id\" = (\"Id\" - 10) WHERE (\"Id\" = 1)", sql); + sql = update.Set(a => a.Id - incrv).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Id\" = (\"Id\" - 10) WHERE (\"Id\" = 1)", sql); - sql = update.Set(a => a.CreateTime.AddYears(1)).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"CreateTime\" = datetime(\"CreateTime\",(1)||' years') WHERE (\"Id\" = 1)", sql); + sql = update.Set(a => a.CreateTime.AddYears(1)).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"CreateTime\" = datetime(\"CreateTime\",(1)||' years') WHERE (\"Id\" = 1)", sql); - sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = \"Clicks\" * 10 / 1 WHERE (\"Id\" = 1)", sql); + sql = update.Set(a => a.Clicks == a.Clicks * 10 / 1).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Clicks\" = \"Clicks\" * 10 / 1 WHERE (\"Id\" = 1)", sql); - sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET \"Id\" = 10 WHERE (\"Id\" = 1)", sql); - } - [Fact] - public void SetRaw() { - var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + :incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET clicks = clicks + :incrClick WHERE (\"Id\" = 1)", sql); - } - [Fact] - public void Where() { - var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"Id\" = 1)", sql); + sql = update.Set(a => a.Id == 10).Where(a => a.Id == 1).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET \"Id\" = 10 WHERE (\"Id\" = 1)", sql); + } + [Fact] + public void SetRaw() + { + var sql = update.Where(a => a.Id == 1).SetRaw("clicks = clicks + :incrClick", new { incrClick = 1 }).ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET clicks = clicks + :incrClick WHERE (\"Id\" = 1)", sql); + } + [Fact] + public void Where() + { + var sql = update.Where(a => a.Id == 1).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"Id\" = 1)", sql); - sql = update.Where("id = :id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (id = :id)", sql); + sql = update.Where("id = :id", new { id = 1 }).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (id = :id)", sql); - var item = new Topic { Id = 1, Title = "newtitle" }; - sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"Id\" = 1)", sql); + var item = new Topic { Id = 1, Title = "newtitle" }; + sql = update.Where(item).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"Id\" = 1)", sql); - var items = new List(); - for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); - sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); - Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); - } - [Fact] - public void WhereExists() { + var items = new List(); + for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 }); + sql = update.Where(items).SetRaw("title='newtitle'").ToSql().Replace("\r\n", ""); + Assert.Equal("UPDATE \"tb_topic\" SET title='newtitle' WHERE (\"Id\" IN (1,2,3,4,5,6,7,8,9,10))", sql); + } + [Fact] + public void WhereExists() + { - } - [Fact] - public void ExecuteAffrows() { + } + [Fact] + public void ExecuteAffrows() + { - } - [Fact] - public void ExecuteUpdated() { + } + [Fact] + public void ExecuteUpdated() + { - } + } - [Fact] - public void AsTable() { - Assert.Null(g.sqlite.Update().ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); - } - } + [Fact] + public void AsTable() + { + Assert.Null(g.sqlite.Update().ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite.Update(new[] { 1, 2 }).SetRaw("title='test'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite.Update(new Topic { Id = 1, Title = "test" }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"Id\" = 1 OR \"Id\" = 2)", g.sqlite.Update(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + Assert.Equal("UPDATE \"tb_topicAsTable\" SET title='test1' \r\nWHERE (\"Id\" = 1)", g.sqlite.Update(new { id = 1 }).SetRaw("title='test1'").AsTable(a => "tb_topicAsTable").ToSql()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/BoolNullableTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/BoolNullableTest.cs index 07fd2dab..1d261272 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/BoolNullableTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/BoolNullableTest.cs @@ -2,1561 +2,1595 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.SqliteMapType { - public class BoolNullableTest { - class BoolNullableMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool))] - public bool? tobool { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool? tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool? tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool? toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool? toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool? toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool? tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool? tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool? tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool? tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool? tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool? toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool? toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool? touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool? touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool? toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool? toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool? tostring { get; set; } = true; - } - [Fact] - public void Bool() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item = new BoolNullableMap { tobool = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item = new BoolNullableMap { tobool = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update all - item.tobool = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(true, find.tobool); - - item.tobool = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - item.tobool = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobool, find.tobool); - Assert.Equal(false, find.tobool); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobool); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item = new BoolNullableMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item = new BoolNullableMap { tosbyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(true, find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - item.tosbyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tosbyte, find.tosbyte); - Assert.Equal(false, find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item = new BoolNullableMap { tosbytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(true, find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Equal(false, find.tosbytenullable); - - item.tosbytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.Null(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item = new BoolNullableMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item = new BoolNullableMap { toshort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(true, find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - item.toshort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toshort, find.toshort); - Assert.Equal(false, find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item = new BoolNullableMap { toshortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(true, find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Equal(false, find.toshortnullable); - - item.toshortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.Null(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item = new BoolNullableMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item = new BoolNullableMap { toint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(true, find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.Equal(false, find.toint); - - item.toint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toint, find.toint); - Assert.Equal(false, find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item = new BoolNullableMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item = new BoolNullableMap { tointnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(true, find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Equal(false, find.tointnullable); - - item.tointnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.Null(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item = new BoolNullableMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item = new BoolNullableMap { tolong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(true, find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - item.tolong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tolong, find.tolong); - Assert.Equal(false, find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item = new BoolNullableMap { tolongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(true, find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Equal(false, find.tolongnullable); - - item.tolongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.Null(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item = new BoolNullableMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item = new BoolNullableMap { tobyte = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(true, find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - item.tobyte = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.tobyte, find.tobyte); - Assert.Equal(false, find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item = new BoolNullableMap { tobytenullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(true, find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Equal(false, find.tobytenullable); - - item.tobytenullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.Null(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item = new BoolNullableMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item = new BoolNullableMap { toushort = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(true, find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - item.toushort = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toushort, find.toushort); - Assert.Equal(false, find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item = new BoolNullableMap { toushortnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(true, find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Equal(false, find.toushortnullable); - - item.toushortnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.Null(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item = new BoolNullableMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item = new BoolNullableMap { touint = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(true, find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.Equal(false, find.touint); - - item.touint = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.touint, find.touint); - Assert.Equal(false, find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item = new BoolNullableMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item = new BoolNullableMap { touintnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(true, find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Equal(false, find.touintnullable); - - item.touintnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.Null(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item = new BoolNullableMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item = new BoolNullableMap { toulong = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(true, find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - item.toulong = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.NotEqual(item.toulong, find.toulong); - Assert.Equal(false, find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item = new BoolNullableMap { toulongnullable = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(true, find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Equal(false, find.toulongnullable); - - item.toulongnullable = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.Null(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.sqlite; - var item = new BoolNullableMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item = new BoolNullableMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item = new BoolNullableMap { tostring = null }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(true, find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Equal(false, find.tostring); - - item.tostring = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.Null(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(true, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(false, find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.SqliteMapType +{ + public class BoolNullableTest + { + class BoolNullableMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool))] + public bool? tobool { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool? tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool? tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool? toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool? toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool? toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool? tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool? tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool? tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool? tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool? tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool? toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool? toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool? touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool? touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool? toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool? toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool? tostring { get; set; } = true; + } + [Fact] + public void Bool() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item = new BoolNullableMap { tobool = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item = new BoolNullableMap { tobool = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update all + item.tobool = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(true, find.tobool); + + item.tobool = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + item.tobool = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobool, find.tobool); + Assert.Equal(false, find.tobool); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobool, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobool == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobool == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobool); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobool == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobool == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item = new BoolNullableMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item = new BoolNullableMap { tosbyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(true, find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + item.tosbyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tosbyte, find.tosbyte); + Assert.Equal(false, find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item = new BoolNullableMap { tosbytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(true, find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Equal(false, find.tosbytenullable); + + item.tosbytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.Null(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item = new BoolNullableMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item = new BoolNullableMap { toshort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(true, find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + item.toshort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toshort, find.toshort); + Assert.Equal(false, find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item = new BoolNullableMap { toshortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(true, find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Equal(false, find.toshortnullable); + + item.toshortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.Null(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item = new BoolNullableMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item = new BoolNullableMap { toint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(true, find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.Equal(false, find.toint); + + item.toint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toint, find.toint); + Assert.Equal(false, find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item = new BoolNullableMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item = new BoolNullableMap { tointnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(true, find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Equal(false, find.tointnullable); + + item.tointnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.Null(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item = new BoolNullableMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item = new BoolNullableMap { tolong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(true, find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + item.tolong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tolong, find.tolong); + Assert.Equal(false, find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item = new BoolNullableMap { tolongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(true, find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Equal(false, find.tolongnullable); + + item.tolongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.Null(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item = new BoolNullableMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item = new BoolNullableMap { tobyte = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(true, find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + item.tobyte = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.tobyte, find.tobyte); + Assert.Equal(false, find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobyte == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item = new BoolNullableMap { tobytenullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(true, find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Equal(false, find.tobytenullable); + + item.tobytenullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.Null(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item = new BoolNullableMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item = new BoolNullableMap { toushort = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(true, find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + item.toushort = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toushort, find.toushort); + Assert.Equal(false, find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushort == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item = new BoolNullableMap { toushortnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(true, find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Equal(false, find.toushortnullable); + + item.toushortnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.Null(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item = new BoolNullableMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item = new BoolNullableMap { touint = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(true, find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.Equal(false, find.touint); + + item.touint = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.touint, find.touint); + Assert.Equal(false, find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touint == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item = new BoolNullableMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item = new BoolNullableMap { touintnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(true, find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Equal(false, find.touintnullable); + + item.touintnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.Null(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item = new BoolNullableMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item = new BoolNullableMap { toulong = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(true, find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + item.toulong = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.NotEqual(item.toulong, find.toulong); + Assert.Equal(false, find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulong == null).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == null).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item = new BoolNullableMap { toulongnullable = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(true, find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Equal(false, find.toulongnullable); + + item.toulongnullable = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.Null(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == null).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.sqlite; + var item = new BoolNullableMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item = new BoolNullableMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item = new BoolNullableMap { tostring = null }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(true, find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Equal(false, find.tostring); + + item.tostring = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.Null(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(true, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(false, find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.tostring == false).First()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/BoolTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/BoolTest.cs index 58f1cf1c..846817f5 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/BoolTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/BoolTest.cs @@ -2,1095 +2,1129 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.SqliteMapType { - public class BoolTest { - - class BoolMap { - public Guid id { get; set; } - [Column(MapType = typeof(bool?))] - public bool toboolnullable { get; set; } = true; - - [Column(MapType = typeof(sbyte))] - public bool tosbyte { get; set; } = true; - [Column(MapType = typeof(sbyte?))] - public bool tosbytenullable { get; set; } = true; - - [Column(MapType = typeof(short))] - public bool toshort { get; set; } = true; - - [Column(MapType = typeof(short?))] - public bool toshortnullable { get; set; } = true; - - [Column(MapType = typeof(int))] - public bool toint { get; set; } = true; - - [Column(MapType = typeof(int?))] - public bool tointnullable { get; set; } = true; - - [Column(MapType = typeof(long))] - public bool tolong { get; set; } = true; - [Column(MapType = typeof(long?))] - public bool tolongnullable { get; set; } = true; - - [Column(MapType = typeof(byte))] - public bool tobyte { get; set; } = true; - [Column(MapType = typeof(byte?))] - public bool tobytenullable { get; set; } = true; - - [Column(MapType = typeof(ushort))] - public bool toushort { get; set; } = true; - - [Column(MapType = typeof(ushort?))] - public bool toushortnullable { get; set; } = true; - - [Column(MapType = typeof(uint))] - public bool touint { get; set; } = true; - - [Column(MapType = typeof(uint?))] - public bool touintnullable { get; set; } = true; - - [Column(MapType = typeof(ulong))] - public bool toulong { get; set; } = true; - [Column(MapType = typeof(ulong?))] - public bool toulongnullable { get; set; } = true; - - [Column(MapType = typeof(string))] - public bool tostring { get; set; } = true; - } - - [Fact] - public void BoolNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item = new BoolMap { toboolnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update all - item.toboolnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.True(find.toboolnullable); - - item.toboolnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toboolnullable, find.toboolnullable); - Assert.False(find.toboolnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toboolnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toboolnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByte() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item = new BoolMap { tosbyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update all - item.tosbyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.True(find.tosbyte); - - item.tosbyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbyte, find.tosbyte); - Assert.False(find.tosbyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void SByteNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item = new BoolMap { tosbytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update all - item.tosbytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.True(find.tosbytenullable); - - item.tosbytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tosbytenullable, find.tosbytenullable); - Assert.False(find.tosbytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tosbytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tosbytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Short() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item = new BoolMap { toshort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update all - item.toshort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.True(find.toshort); - - item.toshort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshort, find.toshort); - Assert.False(find.toshort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ShortNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item = new BoolMap { toshortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update all - item.toshortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.True(find.toshortnullable); - - item.toshortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toshortnullable, find.toshortnullable); - Assert.False(find.toshortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toshortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toshortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Int() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item = new BoolMap { toint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update all - item.toint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.True(find.toint); - - item.toint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toint, find.toint); - Assert.False(find.toint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void IntNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item = new BoolMap { tointnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update all - item.tointnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.True(find.tointnullable); - - item.tointnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tointnullable, find.tointnullable); - Assert.False(find.tointnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tointnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tointnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void Long() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item = new BoolMap { tolong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update all - item.tolong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.True(find.tolong); - - item.tolong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolong, find.tolong); - Assert.False(find.tolong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void LongNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item = new BoolMap { tolongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update all - item.tolongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.True(find.tolongnullable); - - item.tolongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tolongnullable, find.tolongnullable); - Assert.False(find.tolongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tolongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tolongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Byte() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item = new BoolMap { tobyte = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update all - item.tobyte = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.True(find.tobyte); - - item.tobyte = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobyte, find.tobyte); - Assert.False(find.tobyte); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobyte); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobyte); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ByteNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item = new BoolMap { tobytenullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update all - item.tobytenullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.True(find.tobytenullable); - - item.tobytenullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tobytenullable, find.tobytenullable); - Assert.False(find.tobytenullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tobytenullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tobytenullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShort() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item = new BoolMap { toushort = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update all - item.toushort = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.True(find.toushort); - - item.toushort = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushort, find.toushort); - Assert.False(find.toushort); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushort); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushort); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UShortNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item = new BoolMap { toushortnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update all - item.toushortnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.True(find.toushortnullable); - - item.toushortnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toushortnullable, find.toushortnullable); - Assert.False(find.toushortnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toushortnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toushortnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UInt() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item = new BoolMap { touint = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update all - item.touint = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.True(find.touint); - - item.touint = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touint, find.touint); - Assert.False(find.touint); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touint); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touint); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void UIntNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item = new BoolMap { touintnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update all - item.touintnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.True(find.touintnullable); - - item.touintnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.touintnullable, find.touintnullable); - Assert.False(find.touintnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.touintnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.touintnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULong() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item = new BoolMap { toulong = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update all - item.toulong = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.True(find.toulong); - - item.toulong = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulong, find.toulong); - Assert.False(find.toulong); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulong); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulong); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void ULongNullable() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item = new BoolMap { toulongnullable = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update all - item.toulongnullable = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.True(find.toulongnullable); - - item.toulongnullable = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.toulongnullable, find.toulongnullable); - Assert.False(find.toulongnullable); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.toulongnullable); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.toulongnullable); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void TimeSpan() { - } - [Fact] - public void TimeSpanNullable() { - } - [Fact] - public void DateTime() { - } - [Fact] - public void DateTimeNullable() { - } - - [Fact] - public void ByteArray() { - } - [Fact] - public void String() { - //insert - var orm = g.sqlite; - var item = new BoolMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item = new BoolMap { tostring = false }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update all - item.tostring = true; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.True(find.tostring); - - item.tostring = false; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.tostring, find.tostring); - Assert.False(find.tostring); - - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.True(find.tostring); - - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.False(find.tostring); - - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - - [Fact] - public void Guid() { - } - [Fact] - public void GuidNullable() { - } - - [Fact] - public void MygisPoint() { - } - [Fact] - public void MygisLineString() { - } - [Fact] - public void MygisPolygon() { - } - [Fact] - public void MygisMultiPoint() { - } - [Fact] - public void MygisMultiLineString() { - } - [Fact] - public void MygisMultiPolygon() { - } - } +namespace FreeSql.Tests.SqliteMapType +{ + public class BoolTest + { + + class BoolMap + { + public Guid id { get; set; } + [Column(MapType = typeof(bool?))] + public bool toboolnullable { get; set; } = true; + + [Column(MapType = typeof(sbyte))] + public bool tosbyte { get; set; } = true; + [Column(MapType = typeof(sbyte?))] + public bool tosbytenullable { get; set; } = true; + + [Column(MapType = typeof(short))] + public bool toshort { get; set; } = true; + + [Column(MapType = typeof(short?))] + public bool toshortnullable { get; set; } = true; + + [Column(MapType = typeof(int))] + public bool toint { get; set; } = true; + + [Column(MapType = typeof(int?))] + public bool tointnullable { get; set; } = true; + + [Column(MapType = typeof(long))] + public bool tolong { get; set; } = true; + [Column(MapType = typeof(long?))] + public bool tolongnullable { get; set; } = true; + + [Column(MapType = typeof(byte))] + public bool tobyte { get; set; } = true; + [Column(MapType = typeof(byte?))] + public bool tobytenullable { get; set; } = true; + + [Column(MapType = typeof(ushort))] + public bool toushort { get; set; } = true; + + [Column(MapType = typeof(ushort?))] + public bool toushortnullable { get; set; } = true; + + [Column(MapType = typeof(uint))] + public bool touint { get; set; } = true; + + [Column(MapType = typeof(uint?))] + public bool touintnullable { get; set; } = true; + + [Column(MapType = typeof(ulong))] + public bool toulong { get; set; } = true; + [Column(MapType = typeof(ulong?))] + public bool toulongnullable { get; set; } = true; + + [Column(MapType = typeof(string))] + public bool tostring { get; set; } = true; + } + + [Fact] + public void BoolNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item = new BoolMap { toboolnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update all + item.toboolnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.True(find.toboolnullable); + + item.toboolnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toboolnullable, find.toboolnullable); + Assert.False(find.toboolnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toboolnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toboolnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toboolnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toboolnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toboolnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByte() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item = new BoolMap { tosbyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update all + item.tosbyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.True(find.tosbyte); + + item.tosbyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbyte, find.tosbyte); + Assert.False(find.tosbyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void SByteNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item = new BoolMap { tosbytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update all + item.tosbytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.True(find.tosbytenullable); + + item.tosbytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tosbytenullable, find.tosbytenullable); + Assert.False(find.tosbytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tosbytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tosbytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tosbytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tosbytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tosbytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Short() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item = new BoolMap { toshort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update all + item.toshort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.True(find.toshort); + + item.toshort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshort, find.toshort); + Assert.False(find.toshort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ShortNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item = new BoolMap { toshortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update all + item.toshortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.True(find.toshortnullable); + + item.toshortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toshortnullable, find.toshortnullable); + Assert.False(find.toshortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toshortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toshortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toshortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toshortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toshortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Int() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item = new BoolMap { toint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update all + item.toint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.True(find.toint); + + item.toint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toint, find.toint); + Assert.False(find.toint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void IntNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item = new BoolMap { tointnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update all + item.tointnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.True(find.tointnullable); + + item.tointnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tointnullable, find.tointnullable); + Assert.False(find.tointnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tointnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tointnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tointnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tointnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tointnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tointnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void Long() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item = new BoolMap { tolong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update all + item.tolong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.True(find.tolong); + + item.tolong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolong, find.tolong); + Assert.False(find.tolong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void LongNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item = new BoolMap { tolongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update all + item.tolongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.True(find.tolongnullable); + + item.tolongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tolongnullable, find.tolongnullable); + Assert.False(find.tolongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tolongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tolongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tolongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tolongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tolongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Byte() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item = new BoolMap { tobyte = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update all + item.tobyte = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.True(find.tobyte); + + item.tobyte = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobyte, find.tobyte); + Assert.False(find.tobyte); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobyte); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobyte, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobyte == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobyte); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobyte == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobyte == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ByteNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item = new BoolMap { tobytenullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update all + item.tobytenullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.True(find.tobytenullable); + + item.tobytenullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tobytenullable, find.tobytenullable); + Assert.False(find.tobytenullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tobytenullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tobytenullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tobytenullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tobytenullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tobytenullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShort() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item = new BoolMap { toushort = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update all + item.toushort = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.True(find.toushort); + + item.toushort = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushort, find.toushort); + Assert.False(find.toushort); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushort); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushort, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushort == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushort); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushort == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushort == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UShortNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item = new BoolMap { toushortnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update all + item.toushortnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.True(find.toushortnullable); + + item.toushortnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toushortnullable, find.toushortnullable); + Assert.False(find.toushortnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toushortnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toushortnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toushortnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toushortnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toushortnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UInt() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item = new BoolMap { touint = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update all + item.touint = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.True(find.touint); + + item.touint = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touint, find.touint); + Assert.False(find.touint); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touint); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touint, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touint == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touint); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touint == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touint == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void UIntNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item = new BoolMap { touintnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update all + item.touintnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.True(find.touintnullable); + + item.touintnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.touintnullable, find.touintnullable); + Assert.False(find.touintnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.touintnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.touintnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.touintnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.touintnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.touintnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.touintnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULong() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item = new BoolMap { toulong = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update all + item.toulong = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.True(find.toulong); + + item.toulong = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulong, find.toulong); + Assert.False(find.toulong); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulong); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulong, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulong == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulong); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulong == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulong == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void ULongNullable() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item = new BoolMap { toulongnullable = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update all + item.toulongnullable = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.True(find.toulongnullable); + + item.toulongnullable = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.toulongnullable, find.toulongnullable); + Assert.False(find.toulongnullable); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.toulongnullable); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.toulongnullable, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.toulongnullable == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.toulongnullable); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.toulongnullable == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void TimeSpan() + { + } + [Fact] + public void TimeSpanNullable() + { + } + [Fact] + public void DateTime() + { + } + [Fact] + public void DateTimeNullable() + { + } + + [Fact] + public void ByteArray() + { + } + [Fact] + public void String() + { + //insert + var orm = g.sqlite; + var item = new BoolMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item = new BoolMap { tostring = false }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update all + item.tostring = true; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.True(find.tostring); + + item.tostring = false; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.tostring, find.tostring); + Assert.False(find.tostring); + + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, true).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == true).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.True(find.tostring); + + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.tostring, false).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.tostring == false).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.False(find.tostring); + + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.tostring == true).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.tostring == false).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + + [Fact] + public void Guid() + { + } + [Fact] + public void GuidNullable() + { + } + + [Fact] + public void MygisPoint() + { + } + [Fact] + public void MygisLineString() + { + } + [Fact] + public void MygisPolygon() + { + } + [Fact] + public void MygisMultiPoint() + { + } + [Fact] + public void MygisMultiLineString() + { + } + [Fact] + public void MygisMultiPolygon() + { + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/EnumTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/EnumTest.cs index ebb4b471..1797019c 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/EnumTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/EnumTest.cs @@ -3,252 +3,259 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.SqliteMapType { - public class EnumTest { - class EnumTestMap { - public Guid id { get; set; } +namespace FreeSql.Tests.SqliteMapType +{ + public class EnumTest + { + class EnumTestMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(int))] - public ToStringMapEnum enum_to_int { get; set; } - [Column(MapType = typeof(int?))] - public ToStringMapEnum? enumnullable_to_int { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void EnumToString() { - //insert - var orm = g.sqlite; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(int))] + public ToStringMapEnum enum_to_int { get; set; } + [Column(MapType = typeof(int?))] + public ToStringMapEnum? enumnullable_to_int { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void EnumToString() + { + //insert + var orm = g.sqlite; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new EnumTestMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToString() { - //insert - var orm = g.sqlite; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToString() + { + //insert + var orm = g.sqlite; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new EnumTestMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void EnumToInt() { - //insert - var orm = g.sqlite; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + [Fact] + public void EnumToInt() + { + //insert + var orm = g.sqlite; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + item = new EnumTestMap { enum_to_int = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //update all - item.enum_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update all + item.enum_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - item.enum_to_int = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_int, find.enum_to_int); - Assert.Equal(ToStringMapEnum.й, find.enum_to_int); + item.enum_to_int = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_int, find.enum_to_int); + Assert.Equal(ToStringMapEnum.й, find.enum_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullableToInt() { - //insert - var orm = g.sqlite; - var item = new EnumTestMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_int == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullableToInt() + { + //insert + var orm = g.sqlite; + var item = new EnumTestMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); + item = new EnumTestMap { enumnullable_to_int = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_int); - //update all - item.enumnullable_to_int = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); + //update all + item.enumnullable_to_int = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_int); - item.enumnullable_to_int = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); - Assert.Null(find.enumnullable_to_int); + item.enumnullable_to_int = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_int, find.enumnullable_to_int); + Assert.Null(find.enumnullable_to_int); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_int); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_int); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_int, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_int == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_int); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_int == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/ToStringTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/ToStringTest.cs index 0b83f04a..c71a4753 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/ToStringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/MapType/ToStringTest.cs @@ -3,555 +3,568 @@ using System; using System.Numerics; using Xunit; -namespace FreeSql.Tests.SqliteMapType { - public class ToStringTest { - class ToStringMap { - public Guid id { get; set; } +namespace FreeSql.Tests.SqliteMapType +{ + public class ToStringTest + { + class ToStringMap + { + public Guid id { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan timespan_to_string { get; set; } - [Column(MapType = typeof(string))] - public TimeSpan? timespannullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan timespan_to_string { get; set; } + [Column(MapType = typeof(string))] + public TimeSpan? timespannullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime datetime_to_string { get; set; } - [Column(MapType = typeof(string))] - public DateTime? datetimenullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime datetime_to_string { get; set; } + [Column(MapType = typeof(string))] + public DateTime? datetimenullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid guid_to_string { get; set; } - [Column(MapType = typeof(string))] - public Guid? guidnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid guid_to_string { get; set; } + [Column(MapType = typeof(string))] + public Guid? guidnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum enum_to_string { get; set; } - [Column(MapType = typeof(string))] - public ToStringMapEnum? enumnullable_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum enum_to_string { get; set; } + [Column(MapType = typeof(string))] + public ToStringMapEnum? enumnullable_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger biginteger_to_string { get; set; } - [Column(MapType = typeof(string))] - public BigInteger? bigintegernullable_to_string { get; set; } - } - public enum ToStringMapEnum { й, abc, } - [Fact] - public void Enum1() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + [Column(MapType = typeof(string))] + public BigInteger biginteger_to_string { get; set; } + [Column(MapType = typeof(string))] + public BigInteger? bigintegernullable_to_string { get; set; } + } + public enum ToStringMapEnum { й, abc, } + [Fact] + public void Enum1() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + item = new ToStringMap { enum_to_string = ToStringMapEnum.abc }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //update all - item.enum_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update all + item.enum_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - item.enum_to_string = ToStringMapEnum.й; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enum_to_string, find.enum_to_string); - Assert.Equal(ToStringMapEnum.й, find.enum_to_string); + item.enum_to_string = ToStringMapEnum.й; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enum_to_string, find.enum_to_string); + Assert.Equal(ToStringMapEnum.й, find.enum_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum., find.enum_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum., find.enum_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enum_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enum_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void EnumNullable() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enum_to_string == ToStringMapEnum.abc).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void EnumNullable() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); + item = new ToStringMap { enumnullable_to_string = ToStringMapEnum.й }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum.й, find.enumnullable_to_string); - //update all - item.enumnullable_to_string = ToStringMapEnum.; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); + //update all + item.enumnullable_to_string = ToStringMapEnum.; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Equal(ToStringMapEnum., find.enumnullable_to_string); - item.enumnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); - Assert.Null(find.enumnullable_to_string); + item.enumnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.enumnullable_to_string, find.enumnullable_to_string); + Assert.Null(find.enumnullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, ToStringMapEnum.abc).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(ToStringMapEnum.abc, find.enumnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); - find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.enumnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.enumnullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.abc).First()); + find = orm.Select().Where(a => a.id == item.id && a.enumnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.enumnullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigInteger1() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(0, find.biginteger_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.й).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == ToStringMapEnum.).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.enumnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigInteger1() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 0).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(0, find.biginteger_to_string); - item = new ToStringMap { biginteger_to_string = 100 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(100, find.biginteger_to_string); + item = new ToStringMap { biginteger_to_string = 100 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 100).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(100, find.biginteger_to_string); - //update all - item.biginteger_to_string = 200; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(200, find.biginteger_to_string); + //update all + item.biginteger_to_string = 200; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 200).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(200, find.biginteger_to_string); - item.biginteger_to_string = 205; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); - Assert.Equal(205, find.biginteger_to_string); + item.biginteger_to_string = 205; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 205).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.biginteger_to_string, find.biginteger_to_string); + Assert.Equal(205, find.biginteger_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(522, find.biginteger_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 522).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 522).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(522, find.biginteger_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(10005, find.biginteger_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.biginteger_to_string, 10005).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.biginteger_to_string == 10005).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(10005, find.biginteger_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void BigIntegerNullable() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 522).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 205).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.biginteger_to_string == 10005).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void BigIntegerNullable() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - item = new ToStringMap { bigintegernullable_to_string = 101 }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(101, find.bigintegernullable_to_string); + item = new ToStringMap { bigintegernullable_to_string = 101 }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 101).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(101, find.bigintegernullable_to_string); - //update all - item.bigintegernullable_to_string = 2004; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Equal(2004, find.bigintegernullable_to_string); + //update all + item.bigintegernullable_to_string = 2004; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Equal(2004, find.bigintegernullable_to_string); - item.bigintegernullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); - Assert.Null(find.bigintegernullable_to_string); + item.bigintegernullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.bigintegernullable_to_string, find.bigintegernullable_to_string); + Assert.Null(find.bigintegernullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(998, find.bigintegernullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, 998).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(998, find.bigintegernullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); - find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.bigintegernullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.bigintegernullable_to_string, null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).First()); + find = orm.Select().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.bigintegernullable_to_string); - //delete - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); - Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpan1() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.Zero, find.timespan_to_string); + //delete + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 998).ExecuteAffrows()); + Assert.Equal(0, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == 2004).ExecuteAffrows()); + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.bigintegernullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpan1() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.Zero, find.timespan_to_string); - item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); + item = new ToStringMap { timespan_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespan_to_string); - //update all - item.timespan_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespan_to_string, find.timespan_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); + //update all + item.timespan_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespan_to_string, find.timespan_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespan_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespan_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespan_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void TimeSpanNullable() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void TimeSpanNullable() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); + item = new ToStringMap { timespannullable_to_string = TimeSpan.FromDays(1) }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromDays(1), find.timespannullable_to_string); - //update all - item.timespannullable_to_string = TimeSpan.FromHours(10); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); + //update all + item.timespannullable_to_string = TimeSpan.FromHours(10); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Equal(TimeSpan.FromHours(10), find.timespannullable_to_string); - item.timespannullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); - Assert.Null(find.timespannullable_to_string); + item.timespannullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.timespannullable_to_string, find.timespannullable_to_string); + Assert.Null(find.timespannullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, TimeSpan.FromHours(11)).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(TimeSpan.FromHours(11), find.timespannullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.timespannullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.timespannullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.timespannullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTime1() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.MinValue, find.datetime_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTime1() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.MinValue, find.datetime_to_string); - item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); + item = new ToStringMap { datetime_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetime_to_string); - //update all - item.datetime_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetime_to_string, find.datetime_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); + //update all + item.datetime_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetime_to_string, find.datetime_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetime_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetime_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetime_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void DateTimeNullable() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void DateTimeNullable() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); + item = new ToStringMap { datetimenullable_to_string = DateTime.Parse("2000-1-1") }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-1"), find.datetimenullable_to_string); - //update all - item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); + //update all + item.datetimenullable_to_string = DateTime.Parse("2000-1-11"); + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Equal(DateTime.Parse("2000-1-11"), find.datetimenullable_to_string); - item.datetimenullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); - Assert.Null(find.datetimenullable_to_string); + item.datetimenullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.datetimenullable_to_string, find.datetimenullable_to_string); + Assert.Null(find.datetimenullable_to_string); - //update set - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); + //update set + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, DateTime.Parse("2000-1-12")).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(DateTime.Parse("2000-1-12"), find.datetimenullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.datetimenullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.datetimenullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.datetimenullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } - [Fact] - public void Guid1() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(Guid.Empty, find.guid_to_string); + [Fact] + public void Guid1() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == Guid.Empty).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(Guid.Empty, find.guid_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guid_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guid_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update all - newid = Guid.NewGuid(); - item.guid_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guid_to_string, find.guid_to_string); - Assert.Equal(newid, find.guid_to_string); + //update all + newid = Guid.NewGuid(); + item.guid_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guid_to_string, find.guid_to_string); + Assert.Equal(newid, find.guid_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guid_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guid_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guid_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guid_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - [Fact] - public void GuidNullable() { - //insert - var orm = g.sqlite; - var item = new ToStringMap { }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guid_to_string == newid).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + [Fact] + public void GuidNullable() + { + //insert + var orm = g.sqlite; + var item = new ToStringMap { }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + var find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - var newid = Guid.NewGuid(); - item = new ToStringMap { guidnullable_to_string = newid }; - Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + var newid = Guid.NewGuid(); + item = new ToStringMap { guidnullable_to_string = newid }; + Assert.Equal(1, orm.Insert().AppendData(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - //update all - newid = Guid.NewGuid(); - item.guidnullable_to_string = newid; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Equal(newid, find.guidnullable_to_string); + //update all + newid = Guid.NewGuid(); + item.guidnullable_to_string = newid; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Equal(newid, find.guidnullable_to_string); - item.guidnullable_to_string = null; - Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); - Assert.Null(find.guidnullable_to_string); + item.guidnullable_to_string = null; + Assert.Equal(1, orm.Update().SetSource(item).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(item.guidnullable_to_string, find.guidnullable_to_string); + Assert.Null(find.guidnullable_to_string); - //update set - newid = Guid.NewGuid(); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Equal(newid, find.guidnullable_to_string); + //update set + newid = Guid.NewGuid(); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, newid).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == newid).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Equal(newid, find.guidnullable_to_string); - Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); - find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); - Assert.NotNull(find); - Assert.Equal(item.id, find.id); - Assert.Null(find.guidnullable_to_string); + Assert.Equal(1, orm.Update().Where(a => a.id == item.id).Set(a => a.guidnullable_to_string, null).ExecuteAffrows()); + find = orm.Select().Where(a => a.id == item.id && a.guidnullable_to_string == null).First(); + Assert.NotNull(find); + Assert.Equal(item.id, find.id); + Assert.Null(find.guidnullable_to_string); - //delete - Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); - Assert.Null(orm.Select().Where(a => a.id == item.id).First()); - } - } + //delete + Assert.Equal(1, orm.Delete().Where(a => a.id == item.id && a.guidnullable_to_string == null).ExecuteAffrows()); + Assert.Null(orm.Select().Where(a => a.id == item.id).First()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteAdo/SqliteAdoTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteAdo/SqliteAdoTest.cs index 59dafe55..02bb40dc 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteAdo/SqliteAdoTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteAdo/SqliteAdoTest.cs @@ -2,68 +2,80 @@ using FreeSql.DataAnnotations; using System; using Xunit; -namespace FreeSql.Tests.Sqlite { - public class SqliteAdoTest { - [Fact] - public void Pool() { - var t1 = g.sqlite.Ado.MasterPool.StatisticsFullily; - } +namespace FreeSql.Tests.Sqlite +{ + public class SqliteAdoTest + { + [Fact] + public void Pool() + { + var t1 = g.sqlite.Ado.MasterPool.StatisticsFullily; + } - [Fact] - public void SlavePools() { - var t2 = g.sqlite.Ado.SlavePools.Count; - } - [Fact] - public void ExecuteReader() { - - } - [Fact] - public void ExecuteArray() { - - } - [Fact] - public void ExecuteNonQuery() { - - } - [Fact] - public void ExecuteScalar() { - - } + [Fact] + public void SlavePools() + { + var t2 = g.sqlite.Ado.SlavePools.Count; + } + [Fact] + public void ExecuteReader() + { - [Fact] - public void Query() { + } + [Fact] + public void ExecuteArray() + { - var t0 = g.sqlite.Ado.Query("select * from \"song\""); + } + [Fact] + public void ExecuteNonQuery() + { - var t1 = g.sqlite.Ado.Query("select id, url, create_time from \"song\""); + } + [Fact] + public void ExecuteScalar() + { - var t2 = g.sqlite.Ado.Query("select id, url, create_time test_time from \"song\""); + } - var t3 = g.sqlite.Ado.Query("select * from \"song\""); + [Fact] + public void Query() + { - var t4 = g.sqlite.Ado.Query<(int, string, string)>("select * from \"song\""); + var t0 = g.sqlite.Ado.Query("select * from \"song\""); - var t5 = g.sqlite.Ado.Query("select * from \"song\""); - } + var t1 = g.sqlite.Ado.Query("select id, url, create_time from \"song\""); - [Fact] - public void QueryMultipline() { - var t3 = g.sqlite.Ado.Query("select * from song; select * from song; select * from song"); - } + var t2 = g.sqlite.Ado.Query("select id, url, create_time test_time from \"song\""); - class xxx { - public int Id { get; set; } - public string Path { get; set; } - public string Title2 { get; set; } - } + var t3 = g.sqlite.Ado.Query("select * from \"song\""); - class testallDto { - public int Id { get; set; } - public string Title { get; set; } - public string Url { get; set; } - public DateTime Test_time { get; set; } - public DateTime Create_time { get; set; } - public bool Is_deleted { get; set; } - } - } + var t4 = g.sqlite.Ado.Query<(int, string, string)>("select * from \"song\""); + + var t5 = g.sqlite.Ado.Query("select * from \"song\""); + } + + [Fact] + public void QueryMultipline() + { + var t3 = g.sqlite.Ado.Query("select * from song; select * from song; select * from song"); + } + + class xxx + { + public int Id { get; set; } + public string Path { get; set; } + public string Title2 { get; set; } + } + + class testallDto + { + public int Id { get; set; } + public string Title { get; set; } + public string Url { get; set; } + public DateTime Test_time { get; set; } + public DateTime Create_time { get; set; } + public bool Is_deleted { get; set; } + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteCodeFirstTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteCodeFirstTest.cs index b6a3e8bd..ef0597df 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteCodeFirstTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteCodeFirstTest.cs @@ -6,125 +6,140 @@ using System.Linq; using System.Text; using Xunit; -namespace FreeSql.Tests.Sqlite { - public class SqliteCodeFirstTest { +namespace FreeSql.Tests.Sqlite +{ + public class SqliteCodeFirstTest + { - [Fact] - public void ı_ֶ() { - var sql = g.sqlite.CodeFirst.GetComparisonDDLStatements<ı>(); - g.sqlite.CodeFirst.SyncStructure<ı>(); + [Fact] + public void ı_ֶ() + { + var sql = g.sqlite.CodeFirst.GetComparisonDDLStatements<ı>(); + g.sqlite.CodeFirst.SyncStructure<ı>(); - var item = new ı { - = "Ա", - ʱ = DateTime.Now - }; - Assert.Equal(1, g.sqlite.Insert<ı>().AppendData(item).ExecuteAffrows()); - Assert.NotEqual(Guid.Empty, item.); - var item2 = g.sqlite.Select<ı>().Where(a => a. == item.).First(); - Assert.NotNull(item2); - Assert.Equal(item., item2.); - Assert.Equal(item., item2.); - } - class ı { - [Column(IsPrimary = true)] - public Guid { get; set; } + var item = new ı + { + = "Ա", + ʱ = DateTime.Now + }; + Assert.Equal(1, g.sqlite.Insert<ı>().AppendData(item).ExecuteAffrows()); + Assert.NotEqual(Guid.Empty, item.); + var item2 = g.sqlite.Select<ı>().Where(a => a. == item.).First(); + Assert.NotNull(item2); + Assert.Equal(item., item2.); + Assert.Equal(item., item2.); + } + class ı + { + [Column(IsPrimary = true)] + public Guid { get; set; } - public string { get; set; } + public string { get; set; } - public DateTime ʱ { get; set; } - } + public DateTime ʱ { get; set; } + } - [Fact] - public void AddUniques() { - var sql = g.sqlite.CodeFirst.GetComparisonDDLStatements(); - g.sqlite.CodeFirst.SyncStructure(); - } - [Table(Name = "AddUniquesInfo2", OldName = "AddUniquesInfo")] - class AddUniquesInfo { - public Guid id { get; set; } - [Column(Unique = "uk_phone")] - public string phone { get; set; } + [Fact] + public void AddUniques() + { + var sql = g.sqlite.CodeFirst.GetComparisonDDLStatements(); + g.sqlite.CodeFirst.SyncStructure(); + } + [Table(Name = "AddUniquesInfo2", OldName = "AddUniquesInfo")] + class AddUniquesInfo + { + public Guid id { get; set; } + [Column(Unique = "uk_phone")] + public string phone { get; set; } - [Column(Unique = "uk_group_index, uk_group_index22")] - public string group { get; set; } - [Column(Unique = "uk_group_index")] - public int index { get; set; } - [Column(Unique = "uk_group_index22")] - public string index22 { get; set; } - } + [Column(Unique = "uk_group_index, uk_group_index22")] + public string group { get; set; } + [Column(Unique = "uk_group_index")] + public int index { get; set; } + [Column(Unique = "uk_group_index22")] + public string index22 { get; set; } + } - public class Topic { - public Guid Id { get; set; } - public string Title { get; set; } - public string Content { get; set; } - public DateTime CreateTime { get; set; } - } - [Table(Name = "xxxtb.Comment")] - public class Comment { - public Guid Id { get; set; } - public Guid TopicId { get; set; } - public virtual Topic Topic { get; set; } - public string Nickname { get; set; } - public string Content { get; set; } - public DateTime CreateTime { get; set; } - } + public class Topic + { + public Guid Id { get; set; } + public string Title { get; set; } + public string Content { get; set; } + public DateTime CreateTime { get; set; } + } + [Table(Name = "xxxtb.Comment")] + public class Comment + { + public Guid Id { get; set; } + public Guid TopicId { get; set; } + public virtual Topic Topic { get; set; } + public string Nickname { get; set; } + public string Content { get; set; } + public DateTime CreateTime { get; set; } + } - [Fact] - public void AddField() { + [Fact] + public void AddField() + { - //һ FreeSql.Repository չdotnet add package FreeSql.Repository - var topicRepository = g.sqlite.GetGuidRepository(); - var commentRepository = g.sqlite.GetGuidRepository(); + //һ FreeSql.Repository չdotnet add package FreeSql.Repository + var topicRepository = g.sqlite.GetGuidRepository(); + var commentRepository = g.sqlite.GetGuidRepository(); - //Ӳ - var topic = topicRepository.Insert(new Topic { - Title = "±1", - Content = "1", - CreateTime = DateTime.Now - }); + //Ӳ + var topic = topicRepository.Insert(new Topic + { + Title = "±1", + Content = "1", + CreateTime = DateTime.Now + }); - //10 - var comments = Enumerable.Range(0, 10).Select(a => new Comment { - TopicId = topic.Id, - Nickname = $"dz{a}", - Content = $"{a}", - CreateTime = DateTime.Now - }).ToArray(); - var affrows = commentRepository.Insert(comments); + //10 + var comments = Enumerable.Range(0, 10).Select(a => new Comment + { + TopicId = topic.Id, + Nickname = $"dz{a}", + Content = $"{a}", + CreateTime = DateTime.Now + }).ToArray(); + var affrows = commentRepository.Insert(comments); - var find = commentRepository.Select.Where(a => a.Topic.Title == "±1").ToList(); + var find = commentRepository.Select.Where(a => a.Topic.Title == "±1").ToList(); - var sql = g.sqlite.CodeFirst.GetComparisonDDLStatements(); + var sql = g.sqlite.CodeFirst.GetComparisonDDLStatements(); - var id = g.sqlite.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); + var id = g.sqlite.Insert().AppendData(new TopicAddField { }).ExecuteIdentity(); - //var inserted = g.Sqlite.Insert().AppendData(new TopicAddField { }).ExecuteInserted(); - } + //var inserted = g.Sqlite.Insert().AppendData(new TopicAddField { }).ExecuteInserted(); + } - [Table(Name = "xxxtb.TopicAddField", OldName = "TopicAddField")] - public class TopicAddField { - [Column(IsIdentity = true)] - public int Id { get; set; } + [Table(Name = "xxxtb.TopicAddField", OldName = "TopicAddField")] + public class TopicAddField + { + [Column(IsIdentity = true)] + public int Id { get; set; } - public string name { get; set; } + public string name { get; set; } - [Column(DbType = "varchar(200) not null", OldName = "title2")] - public string title3223 { get; set; } = "10"; + [Column(DbType = "varchar(200) not null", OldName = "title2")] + public string title3223 { get; set; } = "10"; - [Column(IsIgnore = true)] - public DateTime ct { get; set; } = DateTime.Now; - } + [Column(IsIgnore = true)] + public DateTime ct { get; set; } = DateTime.Now; + } - [Fact] - public void GetComparisonDDLStatements() { + [Fact] + public void GetComparisonDDLStatements() + { - var sql = g.sqlite.CodeFirst.GetComparisonDDLStatements(); - if (string.IsNullOrEmpty(sql) == false) { - Assert.Equal(@"CREATE TABLE IF NOT EXISTS ""main"".""tb_alltype"" ( + var sql = g.sqlite.CodeFirst.GetComparisonDDLStatements(); + if (string.IsNullOrEmpty(sql) == false) + { + Assert.Equal(@"CREATE TABLE IF NOT EXISTS ""main"".""tb_alltype"" ( ""Id"" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ""Bool"" BOOLEAN NOT NULL, ""SByte"" SMALLINT NOT NULL, @@ -167,114 +182,117 @@ namespace FreeSql.Tests.Sqlite { ) ; ", sql); - } + } - //sql = g.Sqlite.CodeFirst.GetComparisonDDLStatements(); - } + //sql = g.Sqlite.CodeFirst.GetComparisonDDLStatements(); + } - IInsert insert => g.sqlite.Insert(); - ISelect select => g.sqlite.Select(); + IInsert insert => g.sqlite.Insert(); + ISelect select => g.sqlite.Select(); - [Fact] - public void CurdAllField() { - var item = new TableAllType { }; - item.Id = (int)insert.AppendData(item).ExecuteIdentity(); + [Fact] + public void CurdAllField() + { + var item = new TableAllType { }; + item.Id = (int)insert.AppendData(item).ExecuteIdentity(); - var newitem = select.Where(a => a.Id == item.Id).ToOne(); + var newitem = select.Where(a => a.Id == item.Id).ToOne(); - var item2 = new TableAllType { - Bool = true, - BoolNullable = true, - Byte = 255, - ByteNullable = 127, - Bytes = Encoding.UTF8.GetBytes("й"), - DateTime = DateTime.Now, - DateTimeNullable = DateTime.Now.AddHours(-1), - Decimal = 99.99M, - DecimalNullable = 99.98M, - Double = 999.99, - DoubleNullable = 999.98, - Enum1 = TableAllTypeEnumType1.e5, - Enum1Nullable = TableAllTypeEnumType1.e3, - Enum2 = TableAllTypeEnumType2.f2, - Enum2Nullable = TableAllTypeEnumType2.f3, - Float = 19.99F, - FloatNullable = 19.98F, - Guid = Guid.NewGuid(), - GuidNullable = Guid.NewGuid(), - Int = int.MaxValue, - IntNullable = int.MinValue, - SByte = 100, - SByteNullable = 99, - Short = short.MaxValue, - ShortNullable = short.MinValue, - String = "йstring", - TimeSpan = TimeSpan.FromSeconds(999), - TimeSpanNullable = TimeSpan.FromSeconds(60), - UInt = uint.MaxValue, - UIntNullable = uint.MinValue, - ULong = ulong.MaxValue - 10000000, - ULongNullable = ulong.MinValue, - UShort = ushort.MaxValue, - UShortNullable = ushort.MinValue, - testFielLongNullable = long.MinValue - }; - item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); - var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); + var item2 = new TableAllType + { + Bool = true, + BoolNullable = true, + Byte = 255, + ByteNullable = 127, + Bytes = Encoding.UTF8.GetBytes("й"), + DateTime = DateTime.Now, + DateTimeNullable = DateTime.Now.AddHours(-1), + Decimal = 99.99M, + DecimalNullable = 99.98M, + Double = 999.99, + DoubleNullable = 999.98, + Enum1 = TableAllTypeEnumType1.e5, + Enum1Nullable = TableAllTypeEnumType1.e3, + Enum2 = TableAllTypeEnumType2.f2, + Enum2Nullable = TableAllTypeEnumType2.f3, + Float = 19.99F, + FloatNullable = 19.98F, + Guid = Guid.NewGuid(), + GuidNullable = Guid.NewGuid(), + Int = int.MaxValue, + IntNullable = int.MinValue, + SByte = 100, + SByteNullable = 99, + Short = short.MaxValue, + ShortNullable = short.MinValue, + String = "йstring", + TimeSpan = TimeSpan.FromSeconds(999), + TimeSpanNullable = TimeSpan.FromSeconds(60), + UInt = uint.MaxValue, + UIntNullable = uint.MinValue, + ULong = ulong.MaxValue - 10000000, + ULongNullable = ulong.MinValue, + UShort = ushort.MaxValue, + UShortNullable = ushort.MinValue, + testFielLongNullable = long.MinValue + }; + item2.Id = (int)insert.AppendData(item2).ExecuteIdentity(); + var newitem2 = select.Where(a => a.Id == item2.Id).ToOne(); - var items = select.ToList(); - } + var items = select.ToList(); + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - //public string id2 { get; set; } = "id2=10"; + //public string id2 { get; set; } = "id2=10"; - public bool Bool { get; set; } - public sbyte SByte { get; set; } - public short Short { get; set; } - public int Int { get; set; } - public long Long { get; set; } - public byte Byte { get; set; } - public ushort UShort { get; set; } - public uint UInt { get; set; } - public ulong ULong { get; set; } - public double Double { get; set; } - public float Float { get; set; } - public decimal Decimal { get; set; } - public TimeSpan TimeSpan { get; set; } - public DateTime DateTime { get; set; } - public DateTime DateTimeOffSet { get; set; } - public byte[] Bytes { get; set; } - public string String { get; set; } - public Guid Guid { get; set; } + public bool Bool { get; set; } + public sbyte SByte { get; set; } + public short Short { get; set; } + public int Int { get; set; } + public long Long { get; set; } + public byte Byte { get; set; } + public ushort UShort { get; set; } + public uint UInt { get; set; } + public ulong ULong { get; set; } + public double Double { get; set; } + public float Float { get; set; } + public decimal Decimal { get; set; } + public TimeSpan TimeSpan { get; set; } + public DateTime DateTime { get; set; } + public DateTime DateTimeOffSet { get; set; } + public byte[] Bytes { get; set; } + public string String { get; set; } + public Guid Guid { get; set; } - public bool? BoolNullable { get; set; } - public sbyte? SByteNullable { get; set; } - public short? ShortNullable { get; set; } - public int? IntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? ByteNullable { get; set; } - public ushort? UShortNullable { get; set; } - public uint? UIntNullable { get; set; } - public ulong? ULongNullable { get; set; } - public double? DoubleNullable { get; set; } - public float? FloatNullable { get; set; } - public decimal? DecimalNullable { get; set; } - public TimeSpan? TimeSpanNullable { get; set; } - public DateTime? DateTimeNullable { get; set; } - public DateTime? DateTimeOffSetNullable { get; set; } - public Guid? GuidNullable { get; set; } + public bool? BoolNullable { get; set; } + public sbyte? SByteNullable { get; set; } + public short? ShortNullable { get; set; } + public int? IntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? ByteNullable { get; set; } + public ushort? UShortNullable { get; set; } + public uint? UIntNullable { get; set; } + public ulong? ULongNullable { get; set; } + public double? DoubleNullable { get; set; } + public float? FloatNullable { get; set; } + public decimal? DecimalNullable { get; set; } + public TimeSpan? TimeSpanNullable { get; set; } + public DateTime? DateTimeNullable { get; set; } + public DateTime? DateTimeOffSetNullable { get; set; } + public Guid? GuidNullable { get; set; } - public TableAllTypeEnumType1 Enum1 { get; set; } - public TableAllTypeEnumType1? Enum1Nullable { get; set; } - public TableAllTypeEnumType2 Enum2 { get; set; } - public TableAllTypeEnumType2? Enum2Nullable { get; set; } - } + public TableAllTypeEnumType1 Enum1 { get; set; } + public TableAllTypeEnumType1? Enum1Nullable { get; set; } + public TableAllTypeEnumType2 Enum2 { get; set; } + public TableAllTypeEnumType2? Enum2Nullable { get; set; } + } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/ConvertTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/ConvertTest.cs index 0ce1de72..6f881231 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/ConvertTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/ConvertTest.cs @@ -4,143 +4,166 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqliteExpression { - public class ConvertTest { +namespace FreeSql.Tests.SqliteExpression +{ + public class ConvertTest + { - ISelect select => g.sqlite.Select(); + ISelect select => g.sqlite.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void ToBoolean() { - var data = new List(); - data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); - data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); - } - [Fact] - public void ToByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); - data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); - } - [Fact] - public void ToChar() { - var data = new List(); - data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); - data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); - } - [Fact] - public void ToDateTime() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); - } - [Fact] - public void ToDecimal() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToDouble() { - var data = new List(); - data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt32() { - var data = new List(); - data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); - data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToSByte() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); - data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); - } - [Fact] - public void ToSingle() { - var data = new List(); - data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); - data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); - } - [Fact] - public void ToUInt16() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt32() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); - } - [Fact] - public void ToUInt64() { - var data = new List(); - data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); - data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); - } + [Fact] + public void ToBoolean() + { + var data = new List(); + data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); + data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); + } + [Fact] + public void ToByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); + data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); + } + [Fact] + public void ToChar() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); + data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); + } + [Fact] + public void ToDateTime() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); + } + [Fact] + public void ToDecimal() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToDouble() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt32() + { + var data = new List(); + data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); + data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToSByte() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); + data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); + } + [Fact] + public void ToSingle() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); + data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); + } + [Fact] + public void ToUInt16() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt32() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); + } + [Fact] + public void ToUInt64() + { + var data = new List(); + data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); + data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); + } - [Fact] - public void Guid_Parse() { - var data = new List(); - data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); - } + [Fact] + public void Guid_Parse() + { + var data = new List(); + data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); + } - [Fact] - public void Guid_NewGuid() { - var data = new List(); - //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); - } + [Fact] + public void Guid_NewGuid() + { + var data = new List(); + //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); + } - [Fact] - public void Random() { - var data = new List(); - data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); - data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); - } - } + [Fact] + public void Random() + { + var data = new List(); + data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); + data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/DateTimeTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/DateTimeTest.cs index 7577bd3e..7afc0189 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/DateTimeTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/DateTimeTest.cs @@ -4,664 +4,703 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqliteExpression { - public class DateTimeTest { - - ISelect select => g.sqlite.Select(); - - [Table(Name = "tb_topic111333")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - [Table(Name = "TestTypeInfo333")] - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - public DateTime Time { get; set; } - } - [Table(Name = "TestTypeParentInfo23123")] - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - public DateTime Time2 { get; set; } - } - [Fact] - public void Now() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void UtcNow() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) - } - [Fact] - public void Date() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); - data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) - } - [Fact] - public void TimeOfDay() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) - } - [Fact] - public void DayOfWeek() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) - } - [Fact] - public void Day() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) - } - [Fact] - public void DayOfYear() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) - } - [Fact] - public void Month() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (month(a.`CreateTime`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (month(a__Type.`Time`) > month(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (month(a__Type__Parent.`Time2`) > month(now())) - } - [Fact] - public void Year() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (year(a.`CreateTime`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (year(a__Type.`Time`) > year(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (year(a__Type__Parent.`Time2`) > year(now())) - } - [Fact] - public void Hour() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (hour(a.`CreateTime`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (hour(a__Type.`Time`) > hour(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) - } - [Fact] - public void Minute() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (minute(a.`CreateTime`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (minute(a__Type.`Time`) > minute(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) - } - [Fact] - public void Second() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (second(a.`CreateTime`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (second(a__Type.`Time`) > second(now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (second(a__Type__Parent.`Time2`) > second(now())) - } - [Fact] - public void Millisecond() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) - } - [Fact] - public void AddDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) - } - [Fact] - public void AddHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) - } - [Fact] - public void AddMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) - } - [Fact] - public void AddMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) - } - [Fact] - public void AddMonths() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) - } - [Fact] - public void AddSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) - } - [Fact] - public void AddTicks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) - } - [Fact] - public void AddYears() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a."Id", a."Clicks", a."TypeGuid", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //WHERE (((strftime('%s',a."CreateTime")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) - - //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" - //WHERE (((strftime('%s',a__Type."Time")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) - - //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" - //LEFT JOIN "TestTypeParentInfo23123" a__Type__Parent ON a__Type__Parent."Id" = a__Type."ParentId" - //WHERE (((strftime('%s',a__Type__Parent."Time2")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) - data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a."Id", a."Clicks", a."TypeGuid", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //WHERE (datetime(a."CreateTime",(-((1)*86400))||' seconds') > a."CreateTime") - - //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" - //WHERE (datetime(a__Type."Time",(-((1)*86400))||' seconds') > a."CreateTime") - - //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" - //LEFT JOIN "TestTypeParentInfo23123" a__Type__Parent ON a__Type__Parent."Id" = a__Type."ParentId" - //WHERE (datetime(a__Type__Parent."Time2",(-((1)*86400))||' seconds') > a."CreateTime") - } - [Fact] - public void _ЧͬSubtract() { - var data = new List(); - data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); - //SELECT a."Id", a."Clicks", a."TypeGuid", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //WHERE (((strftime('%s',a."CreateTime")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) - - //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" - //WHERE (((strftime('%s',a__Type."Time")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) - - //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" - //LEFT JOIN "TestTypeParentInfo23123" a__Type__Parent ON a__Type__Parent."Id" = a__Type."ParentId" - //WHERE (((strftime('%s',a__Type__Parent."Time2")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) - data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); - //SELECT a."Id", a."Clicks", a."TypeGuid", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //WHERE (datetime(a."CreateTime",(-((1)*86400))||' seconds') > a."CreateTime") - - //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" - //WHERE (datetime(a__Type."Time",(-((1)*86400))||' seconds') > a."CreateTime") - - //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" - //FROM "tb_topic111333" a - //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" - //LEFT JOIN "TestTypeParentInfo23123" a__Type__Parent ON a__Type__Parent."Id" = a__Type."ParentId" - //WHERE (datetime(a__Type__Parent."Time2",(-((1)*86400))||' seconds') > a."CreateTime") - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) - } - - [Fact] - public void DateTime_Compare() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((a.`CreateTime`) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) - } - [Fact] - public void DateTime_DaysInMonth() { - var data = new List(); - data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); - data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) - } - [Fact] - public void DateTime_Equals() { - var data = new List(); - data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); - data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) - } - [Fact] - public void DateTime_IsLeapYear() { - var data = new List(); - data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); - data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) - } - [Fact] - public void DateTime_Parse() { - var data = new List(); - data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); - data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic111333` a - //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type - //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 - //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent - //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) - } - } +namespace FreeSql.Tests.SqliteExpression +{ + public class DateTimeTest + { + + ISelect select => g.sqlite.Select(); + + [Table(Name = "tb_topic111333")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + [Table(Name = "TestTypeInfo333")] + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + public DateTime Time { get; set; } + } + [Table(Name = "TestTypeParentInfo23123")] + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + public DateTime Time2 { get; set; } + } + [Fact] + public void Now() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void UtcNow() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.UtcNow.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(utc_timestamp(), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MinValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('0001/1/1 0:00:00' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.MaxValue.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(cast('9999/12/31 23:59:59' as datetime), '%Y-%m-%d') as datetime)) + } + [Fact] + public void Date() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Date == DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Time.Date > DateTime.Now.Date).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Date > DateTime.Now.Date).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime) = cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime) > cast(date_format(now(), '%Y-%m-%d') as datetime)); + data.Add(select.Where(a => DateTime.Now.Subtract(a.CreateTime.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Time.Date).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => DateTime.Now.Subtract(a.Type.Parent.Time2.Date).TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((timestampdiff(microsecond, cast(date_format(a.`CreateTime`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type.`Time`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((timestampdiff(microsecond, cast(date_format(a__Type__Parent.`Time2`, '%Y-%m-%d') as datetime), now())) / 1000000) > 0) + } + [Fact] + public void TimeOfDay() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay == DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Time.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.TimeOfDay > DateTime.Now.TimeOfDay).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, date_format(a__Type.`Time`, '1970-1-1 %H:%i:%s.%f'), a__Type.`Time`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, date_format(a__Type__Parent.`Time2`, '1970-1-1 %H:%i:%s.%f'), a__Type__Parent.`Time2`) + 62135596800000000) > (timestampdiff(microsecond, date_format(now(), '1970-1-1 %H:%i:%s.%f'), now()) + 62135596800000000)) + } + [Fact] + public void DayOfWeek() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfWeek > DateTime.Now.DayOfWeek).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((dayofweek(a.`CreateTime`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((dayofweek(a__Type.`Time`) - 1) > (dayofweek(now()) - 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((dayofweek(a__Type__Parent.`Time2`) - 1) > (dayofweek(now()) - 1)) + } + [Fact] + public void Day() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Time.Day > DateTime.Now.Day).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Day > DateTime.Now.Day).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(a.`CreateTime`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(a__Type.`Time`) > dayofmonth(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(a__Type__Parent.`Time2`) > dayofmonth(now())) + } + [Fact] + public void DayOfYear() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Time.DayOfYear > DateTime.Now.DayOfYear).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.DayOfYear > DateTime.Now.DayOfYear).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofyear(a.`CreateTime`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofyear(a__Type.`Time`) > dayofyear(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofyear(a__Type__Parent.`Time2`) > dayofyear(now())) + } + [Fact] + public void Month() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Time.Month > DateTime.Now.Month).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Month > DateTime.Now.Month).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (month(a.`CreateTime`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (month(a__Type.`Time`) > month(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (month(a__Type__Parent.`Time2`) > month(now())) + } + [Fact] + public void Year() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Time.Year > DateTime.Now.Year).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Year > DateTime.Now.Year).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (year(a.`CreateTime`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (year(a__Type.`Time`) > year(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (year(a__Type__Parent.`Time2`) > year(now())) + } + [Fact] + public void Hour() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Time.Hour > DateTime.Now.Hour).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Hour > DateTime.Now.Hour).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (hour(a.`CreateTime`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (hour(a__Type.`Time`) > hour(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (hour(a__Type__Parent.`Time2`) > hour(now())) + } + [Fact] + public void Minute() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Time.Minute > DateTime.Now.Minute).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Minute > DateTime.Now.Minute).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (minute(a.`CreateTime`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (minute(a__Type.`Time`) > minute(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (minute(a__Type__Parent.`Time2`) > minute(now())) + } + [Fact] + public void Second() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Time.Second > DateTime.Now.Second).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Second > DateTime.Now.Second).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (second(a.`CreateTime`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (second(a__Type.`Time`) > second(now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (second(a__Type__Parent.`Time2`) > second(now())) + } + [Fact] + public void Millisecond() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Time.Millisecond > DateTime.Now.Millisecond).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Millisecond > DateTime.Now.Millisecond).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (floor(microsecond(a.`CreateTime`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (floor(microsecond(a__Type.`Time`) / 1000) > floor(microsecond(now()) / 1000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (floor(microsecond(a__Type__Parent.`Time2`) / 1000) > floor(microsecond(now()) / 1000)) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Time.Ticks > DateTime.Now.Ticks).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Ticks > DateTime.Now.Ticks).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((timestampdiff(microsecond, '1970-1-1', a.`CreateTime`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type.`Time`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((timestampdiff(microsecond, '1970-1-1', a__Type__Parent.`Time2`) * 10 + 621355968000000000) > (timestampdiff(microsecond, '1970-1-1', now()) * 10 + 621355968000000000)) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Add(TimeSpan.FromDays(1)) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval ((1 * 86400000000)) microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval ((1 * 86400000000)) microsecond) > now()) + } + [Fact] + public void AddDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddDays(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddDays(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) day) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) day) > now()) + } + [Fact] + public void AddHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddHours(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddHours(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) hour) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) hour) > now()) + } + [Fact] + public void AddMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMilliseconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMilliseconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) * 1000 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) * 1000 microsecond) > now()) + } + [Fact] + public void AddMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMinutes(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMinutes(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) minute) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) minute) > now()) + } + [Fact] + public void AddMonths() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddMonths(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddMonths(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) month) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) month) > now()) + } + [Fact] + public void AddSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddSeconds(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddSeconds(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) second) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) second) > now()) + } + [Fact] + public void AddTicks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddTicks(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddTicks(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) / 10 microsecond) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) / 10 microsecond) > now()) + } + [Fact] + public void AddYears() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1) > DateTime.Now).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (date_add(a.`CreateTime`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (date_add(a__Type.`Time`, interval (1) year) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (date_add(a__Type__Parent.`Time2`, interval (1) year) > now()) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a."Id", a."Clicks", a."TypeGuid", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //WHERE (((strftime('%s',a."CreateTime")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) + + //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" + //WHERE (((strftime('%s',a__Type."Time")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) + + //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" + //LEFT JOIN "TestTypeParentInfo23123" a__Type__Parent ON a__Type__Parent."Id" = a__Type."ParentId" + //WHERE (((strftime('%s',a__Type__Parent."Time2")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) + data.Add(select.Where(a => a.CreateTime.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Time.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.Subtract(TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a."Id", a."Clicks", a."TypeGuid", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //WHERE (datetime(a."CreateTime",(-((1)*86400))||' seconds') > a."CreateTime") + + //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" + //WHERE (datetime(a__Type."Time",(-((1)*86400))||' seconds') > a."CreateTime") + + //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" + //LEFT JOIN "TestTypeParentInfo23123" a__Type__Parent ON a__Type__Parent."Id" = a__Type."ParentId" + //WHERE (datetime(a__Type__Parent."Time2",(-((1)*86400))||' seconds') > a."CreateTime") + } + [Fact] + public void _ЧͬSubtract() + { + var data = new List(); + data.Add(select.Where(a => (a.CreateTime - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Time - DateTime.Now).TotalSeconds > 0).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - DateTime.Now).TotalSeconds > 0).ToList()); + //SELECT a."Id", a."Clicks", a."TypeGuid", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //WHERE (((strftime('%s',a."CreateTime")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) + + //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" + //WHERE (((strftime('%s',a__Type."Time")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) + + //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" + //LEFT JOIN "TestTypeParentInfo23123" a__Type__Parent ON a__Type__Parent."Id" = a__Type."ParentId" + //WHERE (((strftime('%s',a__Type__Parent."Time2")-strftime('%s',datetime(current_timestamp,'localtime')))) > 0) + data.Add(select.Where(a => (a.CreateTime - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Time - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + data.Add(select.Where(a => (a.Type.Parent.Time2 - TimeSpan.FromDays(1)) > a.CreateTime).ToList()); + //SELECT a."Id", a."Clicks", a."TypeGuid", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //WHERE (datetime(a."CreateTime",(-((1)*86400))||' seconds') > a."CreateTime") + + //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" + //WHERE (datetime(a__Type."Time",(-((1)*86400))||' seconds') > a."CreateTime") + + //SELECT a."Id", a."Clicks", a."TypeGuid", a__Type."Guid", a__Type."ParentId", a__Type."Name", a__Type."Time", a."Title", a."CreateTime" + //FROM "tb_topic111333" a + //LEFT JOIN "TestTypeInfo333" a__Type ON a__Type."Guid" = a."TypeGuid" + //LEFT JOIN "TestTypeParentInfo23123" a__Type__Parent ON a__Type__Parent."Id" = a__Type."ParentId" + //WHERE (datetime(a__Type__Parent."Time2",(-((1)*86400))||' seconds') > a."CreateTime") + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).ToString().Equals(DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') = now())) + } + + [Fact] + public void DateTime_Compare() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Time.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + data.Add(select.Where(a => a.Type.Parent.Time2.AddYears(1).CompareTo(DateTime.Now) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((a.`CreateTime`) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((date_add(a__Type.`Time`, interval (1) year)) - (now())) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((date_add(a__Type__Parent.`Time2`, interval (1) year)) - (now())) = 0) + } + [Fact] + public void DateTime_DaysInMonth() + { + var data = new List(); + data.Add(select.Where(a => DateTime.DaysInMonth(a.CreateTime.Year, a.CreateTime.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Time.Year, a.Type.Time.Month) > 30).ToList()); + data.Add(select.Where(a => DateTime.DaysInMonth(a.Type.Parent.Time2.Year, a.Type.Parent.Time2.Month) > 30).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (dayofmonth(last_day(concat(year(a.`CreateTime`), month(a.`CreateTime`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (dayofmonth(last_day(concat(year(a__Type.`Time`), month(a__Type.`Time`), '-01'))) > 30); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (dayofmonth(last_day(concat(year(a__Type__Parent.`Time2`), month(a__Type__Parent.`Time2`), '-01'))) > 30) + } + [Fact] + public void DateTime_Equals() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Equals(a.CreateTime.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Time.AddYears(1), DateTime.Now)).ToList()); + data.Add(select.Where(a => DateTime.Equals(a.Type.Parent.Time2.AddYears(1), DateTime.Now)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE ((date_add(a.`CreateTime`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE ((date_add(a__Type.`Time`, interval (1) year) = now())); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE ((date_add(a__Type__Parent.`Time2`, interval (1) year) = now())) + } + [Fact] + public void DateTime_IsLeapYear() + { + var data = new List(); + data.Add(select.Where(a => DateTime.IsLeapYear(a.CreateTime.Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Time.AddYears(1).Year)).ToList()); + data.Add(select.Where(a => DateTime.IsLeapYear(a.Type.Parent.Time2.AddYears(1).Year)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (((year(a.`CreateTime`)) % 4 = 0 AND (year(a.`CreateTime`)) % 100 <> 0 OR (year(a.`CreateTime`)) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (((year(date_add(a__Type.`Time`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type.`Time`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type.`Time`, interval (1) year))) % 400 = 0)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (((year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 4 = 0 AND (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 100 <> 0 OR (year(date_add(a__Type__Parent.`Time2`, interval (1) year))) % 400 = 0)) + } + [Fact] + public void DateTime_Parse() + { + var data = new List(); + data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Time.AddYears(1).ToString()) > DateTime.Now).ToList()); + data.Add(select.Where(a => DateTime.Parse(a.Type.Parent.Time2.AddYears(1).ToString()) > DateTime.Now).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic111333` a + //WHERE (cast(date_format(a.`CreateTime`, '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type + //WHERE (cast(date_format(date_add(a__Type.`Time`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a__Type.`Time` as7, a.`Title` as8, a.`CreateTime` as9 + //FROM `tb_topic111333` a, `TestTypeInfo333` a__Type, `TestTypeParentInfo23123` a__Type__Parent + //WHERE (cast(date_format(date_add(a__Type__Parent.`Time2`, interval (1) year), '%Y-%m-%d %H:%i:%s.%f') as datetime) > now()) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/MathTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/MathTest.cs index 0f0bb32a..3183a14d 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/MathTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/MathTest.cs @@ -4,129 +4,153 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqliteExpression { - public class MathTest { +namespace FreeSql.Tests.SqliteExpression +{ + public class MathTest + { - ISelect select => g.sqlite.Select(); + ISelect select => g.sqlite.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } + public List Types { get; set; } + } - [Fact] - public void PI() { - var data = new List(); - data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); - } - [Fact] - public void Abs() { - var data = new List(); - data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Sign() { - var data = new List(); - data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); - } - [Fact] - public void Floor() { - var data = new List(); - data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); - } - [Fact] - public void Ceiling() { - var data = new List(); - data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Round() { - var data = new List(); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); - data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); - } - [Fact] - public void Exp() { - var data = new List(); - data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log() { - var data = new List(); - data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Log10() { - var data = new List(); - data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Pow() { - var data = new List(); - data.Add(select.Where(a => Math.Pow(2, a.Clicks % 5) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sqrt() { - var data = new List(); - data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Cos() { - var data = new List(); - data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Sin() { - var data = new List(); - data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Tan() { - var data = new List(); - data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Acos() { - var data = new List(); - //data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Asin() { - var data = new List(); - //data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan() { - var data = new List(); - data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); - } - [Fact] - public void Atan2() { - var data = new List(); - //data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); - } - [Fact] - public void Truncate() { - var data = new List(); - //data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); - } - } + [Fact] + public void PI() + { + var data = new List(); + data.Add(select.Where(a => Math.PI + a.Clicks > 0).ToList()); + } + [Fact] + public void Abs() + { + var data = new List(); + data.Add(select.Where(a => Math.Abs(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Sign() + { + var data = new List(); + data.Add(select.Where(a => Math.Sign(-a.Clicks) > 0).ToList()); + } + [Fact] + public void Floor() + { + var data = new List(); + data.Add(select.Where(a => Math.Floor(a.Clicks + 0.5) == a.Clicks).ToList()); + } + [Fact] + public void Ceiling() + { + var data = new List(); + data.Add(select.Where(a => Math.Ceiling(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Round() + { + var data = new List(); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5) == a.Clicks).ToList()); + data.Add(select.Where(a => Math.Round(a.Clicks + 0.5, 1) > a.Clicks).ToList()); + } + [Fact] + public void Exp() + { + var data = new List(); + data.Add(select.Where(a => Math.Exp(1) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log() + { + var data = new List(); + data.Add(select.Where(a => Math.Log(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Log10() + { + var data = new List(); + data.Add(select.Where(a => Math.Log10(a.Clicks + 0.5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Pow() + { + var data = new List(); + data.Add(select.Where(a => Math.Pow(2, a.Clicks % 5) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sqrt() + { + var data = new List(); + data.Add(select.Where(a => Math.Sqrt(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Cos() + { + var data = new List(); + data.Add(select.Where(a => Math.Cos(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Sin() + { + var data = new List(); + data.Add(select.Where(a => Math.Sin(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Tan() + { + var data = new List(); + data.Add(select.Where(a => Math.Tan(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Acos() + { + var data = new List(); + //data.Add(select.Where(a => Math.Acos(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Asin() + { + var data = new List(); + //data.Add(select.Where(a => Math.Asin(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan() + { + var data = new List(); + data.Add(select.Where(a => Math.Atan(Math.Pow(2, a.Clicks % 5)) == a.Clicks + 1).ToList()); + } + [Fact] + public void Atan2() + { + var data = new List(); + //data.Add(select.Where(a => Math.Atan2(2, a.Clicks) == a.Clicks + 1).ToList()); + } + [Fact] + public void Truncate() + { + var data = new List(); + //data.Add(select.Where(a => Math.Truncate(a.Clicks * 1.0 / 3) == a.Clicks + 1).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/OtherTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/OtherTest.cs index 60985b66..020d405b 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/OtherTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/OtherTest.cs @@ -4,109 +4,115 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqliteExpression { - public class OtherTest { +namespace FreeSql.Tests.SqliteExpression +{ + public class OtherTest + { - ISelect select => g.sqlite.Select(); + ISelect select => g.sqlite.Select(); - public OtherTest() { - } + public OtherTest() + { + } - [Fact] - public void Boolean() { - var t1 = select.Where(a => a.Bool == true).ToList(); - var t2 = select.Where(a => a.Bool != true).ToList(); - var t3 = select.Where(a => a.Bool == false).ToList(); - var t4 = select.Where(a => !a.Bool).ToList(); - var t5 = select.Where(a => a.Bool).ToList(); + [Fact] + public void Boolean() + { + var t1 = select.Where(a => a.Bool == true).ToList(); + var t2 = select.Where(a => a.Bool != true).ToList(); + var t3 = select.Where(a => a.Bool == false).ToList(); + var t4 = select.Where(a => !a.Bool).ToList(); + var t5 = select.Where(a => a.Bool).ToList(); - var t11 = select.Where(a => a.BoolNullable == true).ToList(); - var t22 = select.Where(a => a.BoolNullable != true).ToList(); - var t33 = select.Where(a => a.BoolNullable == false).ToList(); - var t44 = select.Where(a => !a.BoolNullable.Value).ToList(); - var t55 = select.Where(a => a.BoolNullable.Value).ToList(); - } + var t11 = select.Where(a => a.BoolNullable == true).ToList(); + var t22 = select.Where(a => a.BoolNullable != true).ToList(); + var t33 = select.Where(a => a.BoolNullable == false).ToList(); + var t44 = select.Where(a => !a.BoolNullable.Value).ToList(); + var t55 = select.Where(a => a.BoolNullable.Value).ToList(); + } - [Fact] - public void Array() { - IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); - var testlinq = select.Where(a => testlinqlist.Contains(a.Int)).ToList(); + [Fact] + public void Array() + { + IEnumerable testlinqlist = new List(new[] { 1, 2, 3 }); + var testlinq = select.Where(a => testlinqlist.Contains(a.Int)).ToList(); - //in not in - var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.Int)).ToList(); - var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.Int) == false).ToList(); - var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.Int)).ToList(); + //in not in + var sql111 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.Int)).ToList(); + var sql112 = select.Where(a => new[] { 1, 2, 3 }.Contains(a.Int) == false).ToList(); + var sql113 = select.Where(a => !new[] { 1, 2, 3 }.Contains(a.Int)).ToList(); - var inarray = new[] { 1, 2, 3 }; - var sql1111 = select.Where(a => inarray.Contains(a.Int)).ToList(); - var sql1122 = select.Where(a => inarray.Contains(a.Int) == false).ToList(); - var sql1133 = select.Where(a => !inarray.Contains(a.Int)).ToList(); + var inarray = new[] { 1, 2, 3 }; + var sql1111 = select.Where(a => inarray.Contains(a.Int)).ToList(); + var sql1122 = select.Where(a => inarray.Contains(a.Int) == false).ToList(); + var sql1133 = select.Where(a => !inarray.Contains(a.Int)).ToList(); - //in not in - var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.Int)).ToList(); - var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.Int) == false).ToList(); - var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.Int)).ToList(); + //in not in + var sql11111 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.Int)).ToList(); + var sql11222 = select.Where(a => new List() { 1, 2, 3 }.Contains(a.Int) == false).ToList(); + var sql11333 = select.Where(a => !new List() { 1, 2, 3 }.Contains(a.Int)).ToList(); - var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.Int)).ToList(); - var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.Int) == false).ToList(); - var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.Int)).ToList(); + var sql11111a = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.Int)).ToList(); + var sql11222b = select.Where(a => new List(new[] { 1, 2, 3 }).Contains(a.Int) == false).ToList(); + var sql11333c = select.Where(a => !new List(new[] { 1, 2, 3 }).Contains(a.Int)).ToList(); - var inarray2 = new List() { 1, 2, 3 }; - var sql111111 = select.Where(a => inarray.Contains(a.Int)).ToList(); - var sql112222 = select.Where(a => inarray.Contains(a.Int) == false).ToList(); - var sql113333 = select.Where(a => !inarray.Contains(a.Int)).ToList(); - } + var inarray2 = new List() { 1, 2, 3 }; + var sql111111 = select.Where(a => inarray.Contains(a.Int)).ToList(); + var sql112222 = select.Where(a => inarray.Contains(a.Int) == false).ToList(); + var sql113333 = select.Where(a => !inarray.Contains(a.Int)).ToList(); + } - [Table(Name = "tb_alltype")] - class TableAllType { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } + [Table(Name = "tb_alltype")] + class TableAllType + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } - public string id2 { get; set; } = "id2=10"; + public string id2 { get; set; } = "id2=10"; - public bool Bool { get; set; } - public sbyte SByte { get; set; } - public short Short { get; set; } - public int Int { get; set; } - public long Long { get; set; } - public byte Byte { get; set; } - public ushort UShort { get; set; } - public uint UInt { get; set; } - public ulong ULong { get; set; } - public double Double { get; set; } - public float Float { get; set; } - public decimal Decimal { get; set; } - public TimeSpan TimeSpan { get; set; } - public DateTime DateTime { get; set; } - public DateTime DateTimeOffSet { get; set; } - public byte[] Bytes { get; set; } - public string String { get; set; } - public Guid Guid { get; set; } + public bool Bool { get; set; } + public sbyte SByte { get; set; } + public short Short { get; set; } + public int Int { get; set; } + public long Long { get; set; } + public byte Byte { get; set; } + public ushort UShort { get; set; } + public uint UInt { get; set; } + public ulong ULong { get; set; } + public double Double { get; set; } + public float Float { get; set; } + public decimal Decimal { get; set; } + public TimeSpan TimeSpan { get; set; } + public DateTime DateTime { get; set; } + public DateTime DateTimeOffSet { get; set; } + public byte[] Bytes { get; set; } + public string String { get; set; } + public Guid Guid { get; set; } - public bool? BoolNullable { get; set; } - public sbyte? SByteNullable { get; set; } - public short? ShortNullable { get; set; } - public int? IntNullable { get; set; } - public long? testFielLongNullable { get; set; } - public byte? ByteNullable { get; set; } - public ushort? UShortNullable { get; set; } - public uint? UIntNullable { get; set; } - public ulong? ULongNullable { get; set; } - public double? DoubleNullable { get; set; } - public float? FloatNullable { get; set; } - public decimal? DecimalNullable { get; set; } - public TimeSpan? TimeSpanNullable { get; set; } - public DateTime? DateTimeNullable { get; set; } - public DateTime? DateTimeOffSetNullable { get; set; } - public Guid? GuidNullable { get; set; } + public bool? BoolNullable { get; set; } + public sbyte? SByteNullable { get; set; } + public short? ShortNullable { get; set; } + public int? IntNullable { get; set; } + public long? testFielLongNullable { get; set; } + public byte? ByteNullable { get; set; } + public ushort? UShortNullable { get; set; } + public uint? UIntNullable { get; set; } + public ulong? ULongNullable { get; set; } + public double? DoubleNullable { get; set; } + public float? FloatNullable { get; set; } + public decimal? DecimalNullable { get; set; } + public TimeSpan? TimeSpanNullable { get; set; } + public DateTime? DateTimeNullable { get; set; } + public DateTime? DateTimeOffSetNullable { get; set; } + public Guid? GuidNullable { get; set; } - public TableAllTypeEnumType1 Enum1 { get; set; } - public TableAllTypeEnumType1? Enum1Nullable { get; set; } - public TableAllTypeEnumType2 Enum2 { get; set; } - public TableAllTypeEnumType2? Enum2Nullable { get; set; } - } + public TableAllTypeEnumType1 Enum1 { get; set; } + public TableAllTypeEnumType1? Enum1Nullable { get; set; } + public TableAllTypeEnumType2 Enum2 { get; set; } + public TableAllTypeEnumType2? Enum2Nullable { get; set; } + } - public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } - [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } - } + public enum TableAllTypeEnumType1 { e1, e2, e3, e5 } + [Flags] public enum TableAllTypeEnumType2 { f1, f2, f3 } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/StringTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/StringTest.cs index b8cc9920..182433ed 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/StringTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/StringTest.cs @@ -4,691 +4,715 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqliteExpression { - public class StringTest { - - ISelect select => g.sqlite.Select(); - - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } - - public List Types { get; set; } - } - class TestEqualsGuid { - public Guid id { get; set; } - } - - [Fact] - public void Equals__() { - var list = new List(); - list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); - list.Add(g.sqlite.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); - } - - [Fact] - public void Empty() { - var data = new List(); - data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ifnull(a.`Title`, '') = '') - } - - [Fact] - public void StartsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) - list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) - } - [Fact] - public void EndsWith() { - var list = new List(); - list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) - } - [Fact] - public void Contains() { - var list = new List(); - list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) - list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); - list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) - } - [Fact] - public void ToLower() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void ToUpper() { - var data = new List(); - data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(a.`Title`) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) - } - [Fact] - public void Substring() { - var data = new List(); - data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) - } - [Fact] - public void Length() { - var data = new List(); - data.Add(select.Where(a => a.Title.Length == 0).ToList()); - data.Add(select.Where(a => a.Title.Length == 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); - data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) - } - [Fact] - public void IndexOf() { - var data = new List(); - data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) - } - [Fact] - public void PadLeft() { - //var data = new List(); - //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); - //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); - //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); - //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - ////FROM `tb_topic` a, `TestTypeInfo` a__Type - ////WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); - //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); - //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); - //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); - //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - ////FROM `tb_topic` a, `TestTypeInfo` a__Type - ////WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void PadRight() { - //var data = new List(); - //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); - //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); - //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); - //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - ////FROM `tb_topic` a, `TestTypeInfo` a__Type - ////WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); - //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); - //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); - //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); - //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - ////FROM `tb_topic` a - ////WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); - - ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - ////FROM `tb_topic` a, `TestTypeInfo` a__Type - ////WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) - } - [Fact] - public void Trim() { - var data = new List(); - data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void TrimStart() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) - } - [Fact] - public void TrimEnd() { - var data = new List(); - data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(a.`Title`) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) - } - [Fact] - public void Replace() { - var data = new List(); - data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); - data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); - data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); - data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); - data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); - - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 - //FROM `tb_topic` a, `TestTypeInfo` a__Type - //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) - } - - [Fact] - public void string_IsNullOrEmpty() { - var data = new List(); - data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); - //data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); - data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); - } - } +namespace FreeSql.Tests.SqliteExpression +{ + public class StringTest + { + + ISelect select => g.sqlite.Select(); + + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } + + public List Types { get; set; } + } + class TestEqualsGuid + { + public Guid id { get; set; } + } + + [Fact] + public void Equals__() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Equals("aaa")).ToList()); + list.Add(g.sqlite.Select().Where(a => a.id.Equals(Guid.Empty)).ToList()); + } + + [Fact] + public void Empty() + { + var data = new List(); + data.Add(select.Where(a => (a.Title ?? "") == string.Empty).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ifnull(a.`Title`, '') = '') + } + + [Fact] + public void StartsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.StartsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`)) + list.Add(select.Where(a => (a.Title + "aaa").StartsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").StartsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`)) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1))) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`)) + } + [Fact] + public void EndsWith() + { + var list = new List(); + list.Add(select.Where(a => a.Title.EndsWith("aaa")).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat(a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").EndsWith("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").EndsWith(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE 'aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat(a__Type.`Name`, '%')) + } + [Fact] + public void Contains() + { + var list = new List(); + list.Add(select.Where(a => a.Title.Contains("aaa")).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => a.Title.Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((a.`Title`) LIKE concat('%', a.`Title` +1, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((a.`Title`) LIKE concat('%', a__Type.`Name`, '%')) + list.Add(select.Where(a => (a.Title + "aaa").Contains("aaa")).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Title + 1)).ToList()); + list.Add(select.Where(a => (a.Title + "aaa").Contains(a.Type.Name)).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE '%aaa%') + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a.`Title`, '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', concat(a.`Title`, 1), '%')) + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE((concat(a.`Title`, 'aaa')) LIKE concat('%', a__Type.`Name`, '%')) + } + [Fact] + public void ToLower() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToLower() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToLower() + "aaa").ToLower() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE(lower(concat(lower(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void ToUpper() + { + var data = new List(); + data.Add(select.Where(a => a.Title.ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(a.`Title`) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(a.`Title`) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.ToUpper() + "aaa").ToUpper() == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (upper(concat(upper(a.`Title`), 'aaa')) = a__Type.`Name`) + } + [Fact] + public void Substring() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Substring(0) == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Substring(0) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(a.`Title`, 1) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(a.`Title`, 1) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(a.Title.Length) == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, a.Title.Length) == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(0, 3) == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Substring(0) + "aaa").Substring(1, 2) == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), char_length(a.`Title`) + 1) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, char_length(a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 1, 3) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (substr(concat(substr(a.`Title`, 1), 'aaa'), 2, 2) = a__Type.`Name`) + } + [Fact] + public void Length() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Length == 0).ToList()); + data.Add(select.Where(a => a.Title.Length == 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => a.Title.Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(a.`Title`) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(a.`Title`) = char_length(a__Type.`Name`)); + data.Add(select.Where(a => (a.Title + "aaa").Length == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Title.Length + 1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").Length == a.Type.Name.Length).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (char_length(concat(a.`Title`, 'aaa')) = char_length(a__Type.`Name`)) + } + [Fact] + public void IndexOf() + { + var data = new List(); + data.Add(select.Where(a => a.Title.IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => a.Title.IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(a.`Title`, 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa") == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == -1).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == (a.Title.Length + 1)).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").IndexOf("aaa", 2) == a.Type.Name.Length + 1).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa') - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = -1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a.`Title`) + 1); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE ((locate(concat(a.`Title`, 'aaa'), 'aaa', 3) - 1) = char_length(a__Type.`Name`) + 1) + } + [Fact] + public void PadLeft() + { + //var data = new List(); + //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == "aaa").ToList()); + //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Title).ToList()); + //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == (a.Title + 1)).ToList()); + //data.Add(select.Where(a => a.Title.PadLeft(10, 'a') == a.Type.Name).ToList()); + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (lpad(a.`Title`, 10, 'a') = 'aaa'); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (lpad(a.`Title`, 10, 'a') = a.`Title`); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (lpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + ////FROM `tb_topic` a, `TestTypeInfo` a__Type + ////WHERE (lpad(a.`Title`, 10, 'a') = a__Type.`Name`); + //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == "aaa").ToList()); + //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Title).ToList()); + //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == (a.Title + 1)).ToList()); + //data.Add(select.Where(a => (a.Title.PadLeft(10, 'a') + "aaa").PadLeft(20, 'b') == a.Type.Name).ToList()); + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + ////FROM `tb_topic` a, `TestTypeInfo` a__Type + ////WHERE (lpad(concat(lpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void PadRight() + { + //var data = new List(); + //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == "aaa").ToList()); + //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Title).ToList()); + //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == (a.Title + 1)).ToList()); + //data.Add(select.Where(a => a.Title.PadRight(10, 'a') == a.Type.Name).ToList()); + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (rpad(a.`Title`, 10, 'a') = 'aaa'); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (rpad(a.`Title`, 10, 'a') = a.`Title`); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (rpad(a.`Title`, 10, 'a') = concat(a.`Title`, 1)); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + ////FROM `tb_topic` a, `TestTypeInfo` a__Type + ////WHERE (rpad(a.`Title`, 10, 'a') = a__Type.`Name`); + //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == "aaa").ToList()); + //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Title).ToList()); + //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == (a.Title + 1)).ToList()); + //data.Add(select.Where(a => (a.Title.PadRight(10, 'a') + "aaa").PadRight(20, 'b') == a.Type.Name).ToList()); + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = 'aaa'); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a.`Title`); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + ////FROM `tb_topic` a + ////WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = concat(a.`Title`, 1)); + + ////SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + ////FROM `tb_topic` a, `TestTypeInfo` a__Type + ////WHERE (rpad(concat(rpad(a.`Title`, 10, 'a'), 'aaa'), 20, 'b') = a__Type.`Name`) + } + [Fact] + public void Trim() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Trim() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Trim() + "aaa").Trim() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Trim('a') + "aaa").Trim('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b') + "aaa").Trim('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Trim('a', 'b', 'c') + "aaa").Trim('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(concat(trim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('a' from concat(trim('a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim('b' from trim('a' from concat(trim('b' from trim('a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim('c' from trim('b' from trim('a' from concat(trim('c' from trim('b' from trim('a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void TrimStart() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from a.`Title`)) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimStart() + "aaa").TrimStart() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a') + "aaa").TrimStart('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b') + "aaa").TrimStart('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimStart('a', 'b', 'c') + "aaa").TrimStart('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (ltrim(concat(ltrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'a' from trim(leading 'a' from a.`Title`)), 'aaa'))) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))), 'aaa'))))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from concat(trim(trailing 'c' from trim(leading 'c' from trim(trailing 'b' from trim(leading 'b' from trim(trailing 'a' from trim(leading 'a' from a.`Title`)))))), 'aaa'))))))) = a__Type.`Name`) + } + [Fact] + public void TrimEnd() + { + var data = new List(); + data.Add(select.Where(a => a.Title.TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(a.`Title`) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from a.`Title`) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from a.`Title`)) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))) = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.TrimEnd() + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a') + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b') + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.TrimEnd('a', 'b', 'c') + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (rtrim(concat(rtrim(a.`Title`), 'aaa')) = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'a' from concat(trim(trailing 'a' from a.`Title`), 'aaa')) = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'b' from trim(trailing 'a' from a.`Title`)), 'aaa'))) = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from concat(trim(trailing 'c' from trim(trailing 'b' from trim(trailing 'a' from a.`Title`))), 'aaa')))) = a__Type.`Name`) + } + [Fact] + public void Replace() + { + var data = new List(); + data.Add(select.Where(a => a.Title.Replace("a", "b") == "aaa").ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c") == a.Title).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") == (a.Title + 1)).ToList()); + data.Add(select.Where(a => a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(a.`Title`, 'a', 'b') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(a.`Title`, 'a', 'b'), 'b', 'c') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a') = a__Type.`Name`); + data.Add(select.Where(a => (a.Title.Replace("a", "b") + "aaa").TrimEnd() == "aaa").ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c") + "aaa").TrimEnd('a') == a.Title).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace("c", "a") + "aaa").TrimEnd('a', 'b') == (a.Title + 1)).ToList()); + data.Add(select.Where(a => (a.Title.Replace("a", "b").Replace("b", "c").Replace(a.Type.Name, "a") + "aaa").TrimEnd('a', 'b', 'c') == a.Type.Name).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(a.`Title`, 'a', 'b'), 'aaa') = 'aaa'); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'aaa') = a.`Title`); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), 'c', 'a'), 'aaa') = concat(a.`Title`, 1)); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (concat(replace(replace(replace(a.`Title`, 'a', 'b'), 'b', 'c'), a__Type.`Name`, 'a'), 'aaa') = a__Type.`Name`) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => a.Title.CompareTo(a.Title + a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(a.`Title`, concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(a.`Title`, concat(a.`Title`, a__Type.`Name`)) = 0); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo("aaa") == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title) > 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Title + 1) == 0).ToList()); + data.Add(select.Where(a => (a.Title + "aaa").CompareTo(a.Type.Name) == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), 'aaa') = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a.`Title`) > 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (strcmp(concat(a.`Title`, 'aaa'), concat(a.`Title`, 1)) = 0); + + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a__Type.`Guid` as4, a__Type.`ParentId` as5, a__Type.`Name` as6, a.`Title` as7, a.`CreateTime` as8 + //FROM `tb_topic` a, `TestTypeInfo` a__Type + //WHERE (strcmp(concat(a.`Title`, 'aaa'), a__Type.`Name`) = 0) + } + + [Fact] + public void string_IsNullOrEmpty() + { + var data = new List(); + data.Add(select.Where(a => string.IsNullOrEmpty(a.Title)).ToList()); + //data.Add(select.Where(a => string.IsNullOrEmpty(a.Title) == false).ToList()); + data.Add(select.Where(a => !string.IsNullOrEmpty(a.Title)).ToList()); + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/TimeSpanTest.cs b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/TimeSpanTest.cs index 74b1fe35..8ad219f6 100644 --- a/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/TimeSpanTest.cs +++ b/FreeSql.Tests/FreeSql.Tests/Sqlite/SqliteExpression/TimeSpanTest.cs @@ -4,257 +4,290 @@ using System.Collections.Generic; using System.Linq; using Xunit; -namespace FreeSql.Tests.SqliteExpression { - public class TimeSpanTest { +namespace FreeSql.Tests.SqliteExpression +{ + public class TimeSpanTest + { - ISelect select => g.sqlite.Select(); + ISelect select => g.sqlite.Select(); - [Table(Name = "tb_topic")] - class Topic { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int Clicks { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - class TestTypeInfo { - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - class TestTypeParentInfo { - public int Id { get; set; } - public string Name { get; set; } + [Table(Name = "tb_topic")] + class Topic + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int Clicks { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + class TestTypeInfo + { + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + class TestTypeParentInfo + { + public int Id { get; set; } + public string Name { get; set; } - public List Types { get; set; } - } - [Fact] - public void Zero() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) - } - [Fact] - public void MinValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) - } - [Fact] - public void MaxValue() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) - } - [Fact] - public void Days() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) - } - [Fact] - public void Hours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) - } - [Fact] - public void Milliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) - } - [Fact] - public void Minutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) - } - [Fact] - public void Seconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) - } - [Fact] - public void Ticks() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) - } - [Fact] - public void TotalDays() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) - } - [Fact] - public void TotalHours() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) - } - [Fact] - public void TotalMilliseconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) - } - [Fact] - public void TotalMinutes() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) - } - [Fact] - public void TotalSeconds() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) - } - [Fact] - public void Add() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) - } - [Fact] - public void Subtract() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) - } - [Fact] - public void CompareTo() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void this_Equals() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void this_ToString() { - var data = new List(); - data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') - } + public List Types { get; set; } + } + [Fact] + public void Zero() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > 0) + } + [Fact] + public void MinValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay > TimeSpan.MinValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) > -922337203685477580) + } + [Fact] + public void MaxValue() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay < TimeSpan.MaxValue).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) < 922337203685477580) + } + [Fact] + public void Days() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Days == 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 86400000000) = 0) + } + [Fact] + public void Hours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Hours > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 3600000000) mod 24 > 0) + } + [Fact] + public void Milliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Milliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000 mod 1000) > 0) + } + [Fact] + public void Minutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Minutes > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 60000000 mod 60) > 0) + } + [Fact] + public void Seconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Seconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) div 1000000 mod 60) > 0) + } + [Fact] + public void Ticks() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Ticks > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) * 10) > 0) + } + [Fact] + public void TotalDays() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalDays > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 86400000000) > 0) + } + [Fact] + public void TotalHours() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalHours > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 3600000000) > 0) + } + [Fact] + public void TotalMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMilliseconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000) > 0) + } + [Fact] + public void TotalMinutes() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalMinutes > 0).ToSql()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 60000000) > 0) + } + [Fact] + public void TotalSeconds() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.TotalSeconds > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) / 1000000) > 0) + } + [Fact] + public void Add() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Add(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) + (1 * 86400000000)) > 0) + } + [Fact] + public void Subtract() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Subtract(TimeSpan.FromDays(1)) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) - (1 * 86400000000)) > 0) + } + [Fact] + public void CompareTo() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.CompareTo(TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void this_Equals() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.Equals(TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void this_ToString() + { + var data = new List(); + data.Add(select.Where(a => a.CreateTime.TimeOfDay.ToString() == "ssss").ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') = 'ssss') + } - [Fact] - public void TimeSpan_Compare() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) - } - [Fact] - public void TimeSpan_Equals() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromDays() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) - } - [Fact] - public void TimeSpan_FromHours() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) - } - [Fact] - public void TimeSpan_FromMilliseconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) - } - [Fact] - public void TimeSpan_FromMinutes() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) - } - [Fact] - public void TimeSpan_FromSeconds() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) - } - [Fact] - public void TimeSpan_FromTicks() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) - } - [Fact] - public void TimeSpan_Parse() { - var data = new List(); - data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); - //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 - //FROM `tb_topic` a - //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) - } - } + [Fact] + public void TimeSpan_Compare() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Compare(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1)) > 0).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) - ((1 * 86400000000))) > 0) + } + [Fact] + public void TimeSpan_Equals() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromDays() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromDays(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 86400000000))) + } + [Fact] + public void TimeSpan_FromHours() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromHours(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 3600000000))) + } + [Fact] + public void TimeSpan_FromMilliseconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMilliseconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000))) + } + [Fact] + public void TimeSpan_FromMinutes() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromMinutes(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 60000000))) + } + [Fact] + public void TimeSpan_FromSeconds() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromSeconds(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 * 1000000))) + } + [Fact] + public void TimeSpan_FromTicks() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Equals(a.CreateTime.TimeOfDay, TimeSpan.FromTicks(1))).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE ((timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000) = (1 / 10))) + } + [Fact] + public void TimeSpan_Parse() + { + var data = new List(); + data.Add(select.Where(a => TimeSpan.Parse(a.CreateTime.TimeOfDay.ToString()) > TimeSpan.Zero).ToList()); + //SELECT a.`Id` as1, a.`Clicks` as2, a.`TypeGuid` as3, a.`Title` as4, a.`CreateTime` as5 + //FROM `tb_topic` a + //WHERE (cast(date_format(date_add(cast('0001/1/1 0:00:00' as datetime), interval (timestampdiff(microsecond, date_format(a.`CreateTime`, '1970-1-1 %H:%i:%s.%f'), a.`CreateTime`) + 62135596800000000)) microsecond), '%Y-%m-%d %H:%i:%s.%f') as signed) > 0) + } + } } diff --git a/FreeSql.Tests/FreeSql.Tests/UnitTest1.cs b/FreeSql.Tests/FreeSql.Tests/UnitTest1.cs index 9695c6a0..e5e93ff3 100644 --- a/FreeSql.Tests/FreeSql.Tests/UnitTest1.cs +++ b/FreeSql.Tests/FreeSql.Tests/UnitTest1.cs @@ -11,428 +11,468 @@ using System.Linq.Expressions; using System.Threading.Tasks; using System.Collections; -namespace FreeSql.Tests { - public class UnitTest1 { - - public class Order { - [Column(IsIdentity = true)] - public int Id { get; set; } - public string OrderTitle { get; set; } - public string CustomerName { get; set; } - public DateTime TransactionDate { get; set; } - public virtual List OrderDetails { get; set; } - } - public class OrderDetail { - [Column(IsIdentity = true)] - public int Id { get; set; } - - public int OrderId { get; set; } - public virtual Order Order { get; set; } - } - - ISelect select => g.mysql.Select(); - - class TestUser { - [Column(IsIdentity = true)] - public int stringid { get; set; } - public string accname { get; set; } - public LogUserOn LogOn { get; set; } - - } - class LogUserOn { - public int id { get; set; } - public int userstrId { get; set; } - } - - class ServiceRequestNew { - public Guid id { get; set; } - public string acptStaffDeptId { get; set; } - public DateTime acptTime { get; set; } - public int crtWrkfmFlag { get; set; } - [Column(DbType = "nvarchar2(1500)")] - public string srvReqstCntt { get; set; } - } - - public class TestEntity : EntityBase { - public int Test { get; set; } - public string Title { get; set; } - public override Task Persistent(IRepositoryUnitOfWork uof) { - uof.GetGuidRepository().Insert(this); - return Task.CompletedTask; - } - public override Task Persistent() { - var res = FreeSqlDb.Insert(this); - res.ExecuteInserted(); - return Task.CompletedTask; - } - } - public abstract class EntityBase : DomainInfrastructure { - [Column(IsPrimary = true, IsIdentity = true)] - public TKey Id { get; set; } - public Guid CompanyId { get; set; } - [Column(IsVersion = true)] - public int Version { get; set; } - } - - public abstract class DomainInfrastructure { - [Column(IsIgnore = true)] - public IFreeSql FreeSqlDb { - get { - return g.sqlite; - } - } - - - public abstract Task Persistent(IRepositoryUnitOfWork uof); - public abstract Task Persistent(); - } - - public class Model1 { - [Column(IsIdentity = true)] - public int id { get; set; } - - public string title { get; set; } - - public ICollection Childs { get; set; } - - public int M2Id { get; set; } - - [Column(IsIgnore = true)] - public List TestManys { get; set; } - - } - - public class Model2 { - - [Column(IsIdentity = true)] - public int id { get; set; } - public string Title { get; set; } - - public Model1 Parent { get; set; } - public int Parent_id { get; set; } - - public string Ccc { get; set; } - public DateTime Date { get; set; } - - [Column(Name = "Waxxx2")] - public int Wa_xxx2 { get; set; } - } - - public class TestEnumable : IEnumerable { - public IEnumerator GetEnumerator() { - throw new NotImplementedException(); - } - - IEnumerator IEnumerable.GetEnumerator() { - throw new NotImplementedException(); - } - } - - public class TestEnum { - public Guid id { get; set; } - public Enum em { get; set; } - } - - /// - /// - /// - [Table(Name = "news_article")] - public class NewsArticle { - /// - /// - /// - [Column(Name = "article_id", IsIdentity = true, IsPrimary = true)] - public int ArticleId { get; set; } - - /// - /// - /// - [Column(Name = "article_title")] - public string ArticleTitle { get; set; } - - /// - /// - /// - [Column(Name = "category_id")] - public int CategoryId { get; set; } - - /// - /// - /// - [Column(Name = "channel_id")] - public int ChannelId { get; set; } - - /// - /// 类型 - /// - [Column(Name = "type_id")] - public int TypeId { get; set; } - - /// - /// 内容简介 - /// - [Column(Name = "summary")] - public string Summary { get; set; } - - /// - /// 缩略图 - /// - [Column(Name = "thumbnail")] - public string Thumbnail { get; set; } - - /// - /// 点击量 - /// - [Column(Name = "hits")] - public int Hits { get; set; } - - /// - /// - /// - [Column(Name = "is_display")] - public int IsDisplay { get; set; } - - /// - /// - /// - [Column(Name = "status")] - public int Status { get; set; } - - /// - /// - /// - [Column(Name = "create_time")] - public int CreateTime { get; set; } - - /// - /// - /// - [Column(Name = "release_time")] - public int ReleaseTime { get; set; } - - public DateTime testaddtime { get; set; } - public DateTime? testaddtime2 { get; set; } - } - - public class NewsArticleDto : NewsArticle { - - } - - - public class TaskBuildInfo { - [FreeSql.DataAnnotations.Column(IsPrimary = true)] - public Guid Id { get; set; } - public Guid TbId { get; set; } - public Guid DataBaseConfigId { get; set; } - public string Name { get; set; } - public int Level { get; set; } - - [Column(IsIgnore = true)] - public virtual TaskBuild TaskBuild { get; set; } - } - public class Templates { - /// - /// 测试中文重命名id - /// - [Column(IsPrimary = true, OldName = "Id")] - public Guid Id2 { get; set; } - public string Title { get; set; } - public DateTime AddTime { get; set; } = DateTime.Now; - public DateTime EditTime { get; set; } - public string Code { get; set; } - } - public class TaskBuild { - - [FreeSql.DataAnnotations.Column(IsPrimary = true)] - public Guid Id { get; set; } - public string TaskName { get; set; } - public Guid TemplatesId { get; set; } - public string GeneratePath { get; set; } - public string FileName { get; set; } - public string NamespaceName { get; set; } - public bool OptionsEntity01 { get; set; } = false; - public bool OptionsEntity02 { get; set; } = false; - public bool OptionsEntity03 { get; set; } = false; - public int OptionsEntity04 { get; set; } - - [Navigate("TbId")] - public virtual ICollection Builds { get; set; } - public Templates Templates { get; set; } - } - - public class SqlFunc { - public static string FormatDateTime() { - return ""; - } - } - - [Fact] - public void Test1() { - - var dcksdkdsk = g.sqlite.Select().Where(a => a.testaddtime2.HasValue).ToSql(); - var dcksdkdsk2 = g.sqlite.Select().Where(a => !a.testaddtime2.HasValue).ToSql(); - - var testgrpsql = g.sqlite.Select() - .From((a, b) => a.InnerJoin(aa => aa.TemplatesId - == b.Id2)) - .GroupBy((a, b) => b.Code) - .ToSql(a => new { - a.Key, - sss = a.Sum(a.Value.Item1.Id), - sss2 = a.Sum(a.Value.Item2.Id2) - }); - - var testgrpsql2 = g.sqlite.Select() - .From((a, b) => a.InnerJoin(aa => aa.TemplatesId - == b.Id2)) - .GroupBy((a, b) => b.Code) - .ToList(a => new { - a.Key, - sss = a.Sum(a.Value.Item1.Id), - sss2 = a.Sum(a.Value.Item2.Id2) - }); - - - var tbid = g.sqlite.Select().First()?.Id ?? Guid.Empty; - - var testarray = new[] { 1, 2, 3 }; - var tbidsql = g.sqlite.Update().Where(a => a.Id == tbid) - .Set(a => new TaskBuild { - FileName = "111", - TaskName = a.TaskName + "333", - OptionsEntity02 = false, - OptionsEntity04 = testarray[0] - }).ToSql(); - - - var dkdkdkd = g.oracle.Select().ToList(); - - - - //var testaddlist = new List(); - //for(var a = 0; a < 133905; a++) { - // testaddlist.Add(new NewsArticle { - // ArticleTitle = "testaddlist_topic" + a, - // Hits = a, - // }); - //} - //g.sqlite.Insert(testaddlist) - // //.NoneParameter() - // .ExecuteAffrows(); - - -g.mysql.Aop.ParseExpression = (s, e) => { - if (e.Expression.NodeType == ExpressionType.Call) { - var callExp = e.Expression as MethodCallExpression; - if (callExp.Object?.Type == typeof(DateTime) && - callExp.Method.Name == "ToString" && - callExp.Arguments.Count == 1 && - callExp.Arguments[0].Type == typeof(string) && - callExp.Arguments[0].NodeType == ExpressionType.Constant) { - var format = (callExp.Arguments[0] as ConstantExpression)?.Value?.ToString(); - - if (string.IsNullOrEmpty(format) == false) { - var tmp = e.FreeParse(callExp.Object); - - switch(format) { - case "yyyy-MM-dd HH:mm": - tmp = $"date_format({tmp}, '%Y-%m-%d %H:%i')"; - break; - } - e.Result = tmp; - } - } - } -}; +namespace FreeSql.Tests +{ + public class UnitTest1 + { + + public class Order + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public string OrderTitle { get; set; } + public string CustomerName { get; set; } + public DateTime TransactionDate { get; set; } + public virtual List OrderDetails { get; set; } + } + public class OrderDetail + { + [Column(IsIdentity = true)] + public int Id { get; set; } + + public int OrderId { get; set; } + public virtual Order Order { get; set; } + } + + ISelect select => g.mysql.Select(); + + class TestUser + { + [Column(IsIdentity = true)] + public int stringid { get; set; } + public string accname { get; set; } + public LogUserOn LogOn { get; set; } + + } + class LogUserOn + { + public int id { get; set; } + public int userstrId { get; set; } + } + + class ServiceRequestNew + { + public Guid id { get; set; } + public string acptStaffDeptId { get; set; } + public DateTime acptTime { get; set; } + public int crtWrkfmFlag { get; set; } + [Column(DbType = "nvarchar2(1500)")] + public string srvReqstCntt { get; set; } + } + + public class TestEntity : EntityBase + { + public int Test { get; set; } + public string Title { get; set; } + public override Task Persistent(IRepositoryUnitOfWork uof) + { + uof.GetGuidRepository().Insert(this); + return Task.CompletedTask; + } + public override Task Persistent() + { + var res = FreeSqlDb.Insert(this); + res.ExecuteInserted(); + return Task.CompletedTask; + } + } + public abstract class EntityBase : DomainInfrastructure + { + [Column(IsPrimary = true, IsIdentity = true)] + public TKey Id { get; set; } + public Guid CompanyId { get; set; } + [Column(IsVersion = true)] + public int Version { get; set; } + } + + public abstract class DomainInfrastructure + { + [Column(IsIgnore = true)] + public IFreeSql FreeSqlDb + { + get + { + return g.sqlite; + } + } + + + public abstract Task Persistent(IRepositoryUnitOfWork uof); + public abstract Task Persistent(); + } + + public class Model1 + { + [Column(IsIdentity = true)] + public int id { get; set; } + + public string title { get; set; } + + public ICollection Childs { get; set; } + + public int M2Id { get; set; } + + [Column(IsIgnore = true)] + public List TestManys { get; set; } + + } + + public class Model2 + { + + [Column(IsIdentity = true)] + public int id { get; set; } + public string Title { get; set; } + + public Model1 Parent { get; set; } + public int Parent_id { get; set; } + + public string Ccc { get; set; } + public DateTime Date { get; set; } + + [Column(Name = "Waxxx2")] + public int Wa_xxx2 { get; set; } + } + + public class TestEnumable : IEnumerable + { + public IEnumerator GetEnumerator() + { + throw new NotImplementedException(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + throw new NotImplementedException(); + } + } + + public class TestEnum + { + public Guid id { get; set; } + public Enum em { get; set; } + } + + /// + /// + /// + [Table(Name = "news_article")] + public class NewsArticle + { + /// + /// + /// + [Column(Name = "article_id", IsIdentity = true, IsPrimary = true)] + public int ArticleId { get; set; } + + /// + /// + /// + [Column(Name = "article_title")] + public string ArticleTitle { get; set; } + + /// + /// + /// + [Column(Name = "category_id")] + public int CategoryId { get; set; } + + /// + /// + /// + [Column(Name = "channel_id")] + public int ChannelId { get; set; } + + /// + /// 类型 + /// + [Column(Name = "type_id")] + public int TypeId { get; set; } + + /// + /// 内容简介 + /// + [Column(Name = "summary")] + public string Summary { get; set; } + + /// + /// 缩略图 + /// + [Column(Name = "thumbnail")] + public string Thumbnail { get; set; } + + /// + /// 点击量 + /// + [Column(Name = "hits")] + public int Hits { get; set; } + + /// + /// + /// + [Column(Name = "is_display")] + public int IsDisplay { get; set; } + + /// + /// + /// + [Column(Name = "status")] + public int Status { get; set; } + + /// + /// + /// + [Column(Name = "create_time")] + public int CreateTime { get; set; } + + /// + /// + /// + [Column(Name = "release_time")] + public int ReleaseTime { get; set; } + + public DateTime testaddtime { get; set; } + public DateTime? testaddtime2 { get; set; } + } + + public class NewsArticleDto : NewsArticle + { + + } + + + public class TaskBuildInfo + { + [FreeSql.DataAnnotations.Column(IsPrimary = true)] + public Guid Id { get; set; } + public Guid TbId { get; set; } + public Guid DataBaseConfigId { get; set; } + public string Name { get; set; } + public int Level { get; set; } + + [Column(IsIgnore = true)] + public virtual TaskBuild TaskBuild { get; set; } + } + public class Templates + { + /// + /// 测试中文重命名id + /// + [Column(IsPrimary = true, OldName = "Id")] + public Guid Id2 { get; set; } + public string Title { get; set; } + public DateTime AddTime { get; set; } = DateTime.Now; + public DateTime EditTime { get; set; } + public string Code { get; set; } + } + public class TaskBuild + { + + [FreeSql.DataAnnotations.Column(IsPrimary = true)] + public Guid Id { get; set; } + public string TaskName { get; set; } + public Guid TemplatesId { get; set; } + public string GeneratePath { get; set; } + public string FileName { get; set; } + public string NamespaceName { get; set; } + public bool OptionsEntity01 { get; set; } = false; + public bool OptionsEntity02 { get; set; } = false; + public bool OptionsEntity03 { get; set; } = false; + public int OptionsEntity04 { get; set; } + + [Navigate("TbId")] + public virtual ICollection Builds { get; set; } + public Templates Templates { get; set; } + } + + public class SqlFunc + { + public static string FormatDateTime() + { + return ""; + } + } + + [Fact] + public void Test1() + { + + var dcksdkdsk = g.sqlite.Select().Where(a => a.testaddtime2.HasValue).ToSql(); + var dcksdkdsk2 = g.sqlite.Select().Where(a => !a.testaddtime2.HasValue).ToSql(); + + var testgrpsql = g.sqlite.Select() + .From((a, b) => a.InnerJoin(aa => aa.TemplatesId + == b.Id2)) + .GroupBy((a, b) => b.Code) + .ToSql(a => new + { + a.Key, + sss = a.Sum(a.Value.Item1.Id), + sss2 = a.Sum(a.Value.Item2.Id2) + }); + + var testgrpsql2 = g.sqlite.Select() + .From((a, b) => a.InnerJoin(aa => aa.TemplatesId + == b.Id2)) + .GroupBy((a, b) => b.Code) + .ToList(a => new + { + a.Key, + sss = a.Sum(a.Value.Item1.Id), + sss2 = a.Sum(a.Value.Item2.Id2) + }); + + + var tbid = g.sqlite.Select().First()?.Id ?? Guid.Empty; + + var testarray = new[] { 1, 2, 3 }; + var tbidsql = g.sqlite.Update().Where(a => a.Id == tbid) + .Set(a => new TaskBuild + { + FileName = "111", + TaskName = a.TaskName + "333", + OptionsEntity02 = false, + OptionsEntity04 = testarray[0] + }).ToSql(); + + + var dkdkdkd = g.oracle.Select().ToList(); + + + + //var testaddlist = new List(); + //for(var a = 0; a < 133905; a++) { + // testaddlist.Add(new NewsArticle { + // ArticleTitle = "testaddlist_topic" + a, + // Hits = a, + // }); + //} + //g.sqlite.Insert(testaddlist) + // //.NoneParameter() + // .ExecuteAffrows(); + + + g.mysql.Aop.ParseExpression = (s, e) => + { + if (e.Expression.NodeType == ExpressionType.Call) + { + var callExp = e.Expression as MethodCallExpression; + if (callExp.Object?.Type == typeof(DateTime) && + callExp.Method.Name == "ToString" && + callExp.Arguments.Count == 1 && + callExp.Arguments[0].Type == typeof(string) && + callExp.Arguments[0].NodeType == ExpressionType.Constant) + { + var format = (callExp.Arguments[0] as ConstantExpression)?.Value?.ToString(); + + if (string.IsNullOrEmpty(format) == false) + { + var tmp = e.FreeParse(callExp.Object); + + switch (format) + { + case "yyyy-MM-dd HH:mm": + tmp = $"date_format({tmp}, '%Y-%m-%d %H:%i')"; + break; + } + e.Result = tmp; + } + } + } + }; + + g.mysql.Select().ToList(a => new + { + testaddtime = a.testaddtime.ToString("yyyy-MM-dd HH:mm") + }); - g.mysql.Select().ToList(a => new { - testaddtime = a.testaddtime.ToString("yyyy-MM-dd HH:mm") - }); + var ttdkdk = g.mysql.Select().Where(a => a.NamespaceName == "ddd").ToSql(); - var ttdkdk = g.mysql.Select().Where(a => a.NamespaceName == "ddd").ToSql(); + var tsqlddd = g.sqlite.Select().Where(a => + g.sqlite.Select().Where(b => b.NamespaceName == a.ArticleTitle) + .Where("@id=1", new { id = 1 }).Any() + ).ToSql(); - var tsqlddd = g.sqlite.Select().Where(a => - g.sqlite.Select().Where(b => b.NamespaceName == a.ArticleTitle) - .Where("@id=1", new { id = 1 }).Any() - ).ToSql(); + g.sqlite.SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = true); + var trepo = g.sqlite.GetGuidRepository(); + trepo.Insert(new TaskBuild + { + TaskName = "tt11", + Builds = new[] { + new TaskBuildInfo { + Level = 1, + Name = "t111_11" + } + } + }); - g.sqlite.SetDbContextOptions(opt => opt.EnableAddOrUpdateNavigateList = true); - var trepo = g.sqlite.GetGuidRepository(); - trepo.Insert(new TaskBuild { - TaskName = "tt11", - Builds = new[] { - new TaskBuildInfo { - Level = 1, - Name = "t111_11" - } - } - }); + var ttdkdkd = trepo.Select.Where(a => a.Builds.AsSelect().Any()).ToList(); - var ttdkdkd = trepo.Select.Where(a => a.Builds.AsSelect().Any()).ToList(); + var list1113233 = trepo.Select.ToList(); - var list1113233 = trepo.Select.ToList(); + var entity = new NewsArticle + { + ArticleId = 1, + ArticleTitle = "测试标题" + }; + var where = new NewsArticle + { + ArticleId = 1, + ChannelId = 1, + }; - var entity = new NewsArticle { - ArticleId = 1, - ArticleTitle = "测试标题" - }; - var where = new NewsArticle { - ArticleId = 1, - ChannelId = 1, - }; + g.mysql.Insert(new[] { entity }).ExecuteAffrows(); - g.mysql.Insert(new[] { entity }).ExecuteAffrows(); + var sqldddkdk = g.mysql.Update(where) + .SetSource(entity) + .UpdateColumns(x => new { x.Status, x.CategoryId, x.ArticleTitle }) + .ToSql(); - var sqldddkdk = g.mysql.Update(where) - .SetSource(entity) - .UpdateColumns(x => new { x.Status, x.CategoryId, x.ArticleTitle }) - .ToSql(); + var sqldddklist = g.mysql.Select().Select(a => new NewsArticleDto { }).ToList(); - var sqldddklist = g.mysql.Select().Select(a => new NewsArticleDto { }).ToList(); + var sql1111333 = g.mysql.Update() + .SetSource(new Model2 { id = 1, Title = "xxx", Parent_id = 0 }) + .UpdateColumns(x => new { x.Parent_id, x.Date, x.Wa_xxx2 }) + .NoneParameter() + .ToSql(); - var sql1111333 = g.mysql.Update() - .SetSource(new Model2 { id = 1, Title = "xxx", Parent_id = 0 }) - .UpdateColumns(x => new { x.Parent_id, x.Date, x.Wa_xxx2 }) - .NoneParameter() - .ToSql(); - - g.sqlite.Insert(new TestEnum { }).ExecuteAffrows(); - var telist = g.sqlite.Select().ToList(); + g.sqlite.Insert(new TestEnum { }).ExecuteAffrows(); + var telist = g.sqlite.Select().ToList(); - Assert.Throws(() => g.sqlite.CodeFirst.SyncStructure()); + Assert.Throws(() => g.sqlite.CodeFirst.SyncStructure()); - var TestEnumable = new TestEnumable(); - + var TestEnumable = new TestEnumable(); - g.sqlite.GetRepository().Insert(new Model1 { - title = "test_" + DateTime.Now.ToString("yyyyMMddHHmmss"), - M2Id = DateTime.Now.Second + DateTime.Now.Minute, - Childs = new[] { - new Model2 { - Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0001", - }, - new Model2 { - Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0002", - }, - new Model2 { - Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0003", - }, - new Model2 { - Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0004", - } - } - }); - var includet1 = g.sqlite.Select() - .IncludeMany(a => a.Childs.Take(2), s => s.Where(a => a.id > 0)) - .IncludeMany(a => a.TestManys.Take(1).Where(b => b.id == a.id)) - .Where(a => a.id > 10) - .ToList(); + g.sqlite.GetRepository().Insert(new Model1 + { + title = "test_" + DateTime.Now.ToString("yyyyMMddHHmmss"), + M2Id = DateTime.Now.Second + DateTime.Now.Minute, + Childs = new[] { + new Model2 { + Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0001", + }, + new Model2 { + Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0002", + }, + new Model2 { + Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0003", + }, + new Model2 { + Title = "model2Test_title_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "0004", + } + } + }); + var includet1 = g.sqlite.Select() + .IncludeMany(a => a.Childs.Take(2), s => s.Where(a => a.id > 0)) + .IncludeMany(a => a.TestManys.Take(1).Where(b => b.id == a.id)) + .Where(a => a.id > 10) + .ToList(); @@ -451,116 +491,124 @@ g.mysql.Aop.ParseExpression = (s, e) => { - var ttt1 = g.sqlite.Select().Where(a => a.Childs.AsSelect().Any(b => b.Title == "111")).ToList(); + var ttt1 = g.sqlite.Select().Where(a => a.Childs.AsSelect().Any(b => b.Title == "111")).ToList(); - var linqto1 = - from p in g.sqlite.Select() - where p.Id >= 0 - // && p.OrderDetails.AsSelect().Where(c => c.Id > 10).Any() - orderby p.Id descending - orderby p.CustomerName ascending - select new { Name = p.CustomerName, Length = p.Id }; + var linqto1 = + from p in g.sqlite.Select() + where p.Id >= 0 + // && p.OrderDetails.AsSelect().Where(c => c.Id > 10).Any() + orderby p.Id descending + orderby p.CustomerName ascending + select new { Name = p.CustomerName, Length = p.Id }; - var testddd = new TestEntity { - Test = 22, - Title = "xxx" - }; - //testddd.Persistent().Wait(); - g.sqlite.GetRepository().Insert(testddd); - var testpid1 = g.mysql.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); - g.mysql.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); + var testddd = new TestEntity + { + Test = 22, + Title = "xxx" + }; + //testddd.Persistent().Wait(); + g.sqlite.GetRepository().Insert(testddd); - var aggsql1 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist1 = select - .GroupBy(a => a.Title) - .ToList(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid) - }); + var testpid1 = g.mysql.Insert().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity(); + g.mysql.Insert().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows(); - var aggsql2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToSql(b => new { - b.Key.Title, - b.Key.yyyy, + var aggsql1 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist1 = select + .GroupBy(a => a.Title) + .ToList(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid) + }); - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); - var aggtolist2 = select - .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) - .ToList(b => new { - b.Key.Title, - b.Key.yyyy, + var aggsql2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToSql(b => new + { + b.Key.Title, + b.Key.yyyy, - cou = b.Count(), - sum = b.Sum(b.Key.yyyy), - sum2 = b.Sum(b.Value.TypeGuid) - }); + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); + var aggtolist2 = select + .GroupBy(a => new { a.Title, yyyy = string.Concat(a.CreateTime.Year, '-', a.CreateTime.Month) }) + .ToList(b => new + { + b.Key.Title, + b.Key.yyyy, - var aggsql3 = select - .GroupBy(a => a.Title) - .ToSql(b => new { - b.Key, - cou = b.Count(), - sum = b.Sum(b.Key), - sum2 = b.Sum(b.Value.TypeGuid), - sum3 = b.Sum(b.Value.Type.Parent.Parent.Id) - }); + cou = b.Count(), + sum = b.Sum(b.Key.yyyy), + sum2 = b.Sum(b.Value.TypeGuid) + }); - var sqlrepos = g.sqlite.GetRepository(); - sqlrepos.Insert(new TestTypeParentInfo { - Name = "testroot", - Childs = new[] { - new TestTypeParentInfo { - Name = "testpath2", - Childs = new[] { - new TestTypeParentInfo { - Name = "testpath3", - Childs = new[] { - new TestTypeParentInfo { - Name = "11" - } - } - } - } - } - } - }); + var aggsql3 = select + .GroupBy(a => a.Title) + .ToSql(b => new + { + b.Key, + cou = b.Count(), + sum = b.Sum(b.Key), + sum2 = b.Sum(b.Value.TypeGuid), + sum3 = b.Sum(b.Value.Type.Parent.Parent.Id) + }); - var sql = g.sqlite.Select().Where(a => a.Parent.Parent.Parent.Name == "testroot").ToSql(); - var sql222 = g.sqlite.Select().Where(a => a.Parent.Parent.Parent.Name == "testroot").ToList(); - - - Expression> orderBy = null; - orderBy = a => a.CreateTime; - var testsql1 = select.OrderBy(orderBy).ToSql(); - - orderBy = a => a.Title; - - var testsql2 = select.OrderBy(orderBy).ToSql(); - - - var testjson = @"[ + var sqlrepos = g.sqlite.GetRepository(); + sqlrepos.Insert(new TestTypeParentInfo + { + Name = "testroot", + Childs = new[] { + new TestTypeParentInfo { + Name = "testpath2", + Childs = new[] { + new TestTypeParentInfo { + Name = "testpath3", + Childs = new[] { + new TestTypeParentInfo { + Name = "11" + } + } + } + } + } + } + }); + + var sql = g.sqlite.Select().Where(a => a.Parent.Parent.Parent.Name == "testroot").ToSql(); + var sql222 = g.sqlite.Select().Where(a => a.Parent.Parent.Parent.Name == "testroot").ToList(); + + + Expression> orderBy = null; + orderBy = a => a.CreateTime; + var testsql1 = select.OrderBy(orderBy).ToSql(); + + orderBy = a => a.Title; + + var testsql2 = select.OrderBy(orderBy).ToSql(); + + + var testjson = @"[ { ""acptNumBelgCityName"":""泰州"", ""concPrsnName"":""常**"", @@ -578,325 +626,355 @@ g.mysql.Aop.ParseExpression = (s, e) => { ""acptStaffDeptId"":""0003002101010001000600020023"" } ]"; - //var dic = Newtonsoft.Json.JsonConvert.DeserializeObject>(testjson); - var reqs = Newtonsoft.Json.JsonConvert.DeserializeObject>(testjson); - reqs.ForEach(t => { - g.oracle.Insert(t).ExecuteAffrows(); - - }); - - - - var sql111 = g.sqlite.Select().AsTable((a, b) => "(select * from TestUser where stringid > 10)").Page(1, 10).ToSql(); - - - var xxx = g.sqlite.Select().GroupBy(a => new { a.stringid }).ToList(a => a.Key.stringid); - - var tuser = g.sqlite.Select().Where(u => u.accname == "admin") - .InnerJoin(a => a.LogOn.id == a.stringid).ToSql(); - - - var parentSelect1 = select.Where(a => a.Type.Parent.Parent.Parent.Parent.Name == "").Where(b => b.Type.Name == "").ToSql(); - - - var collSelect1 = g.mysql.Select().Where(a => - a.OrderDetails.AsSelect().Any(b => b.Id > 100) - ); - - var collectionSelect = select.Where(a => - //a.Type.Guid == a.TypeGuid && - //a.Type.Parent.Id == a.Type.ParentId && - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( - //b => b.ParentId == a.Type.Parent.Id - ) - ); - - var collectionSelect2 = select.Where(a => - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( - b => b.Parent.Name == "xxx" && b.Parent.Parent.Name == "ccc" - && b.Parent.Parent.Parent.Types.AsSelect().Any(cb => cb.Name == "yyy") - ) - ); - - var collectionSelect3 = select.Where(a => - a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( - bbb => bbb.Parent.Types.AsSelect().Where(lv2 => lv2.Name == bbb.Name + "111").Any( - ) - ) - ); - - - var neworder = new Order { - CustomerName = "testCustomer", - OrderTitle = "xxx#cccksksk", - TransactionDate = DateTime.Now, - OrderDetails = new List(new[] { - new OrderDetail { - - }, - new OrderDetail { - - } - }) - }; - - g.mysql.GetRepository().Insert(neworder); - - var order = g.mysql.Select().Where(a => a.Id == neworder.Id).ToOne(); //查询订单表 - if (order == null) { - var orderId = g.mysql.Insert(new Order { }).ExecuteIdentity(); - order = g.mysql.Select(orderId).ToOne(); - } - - - var orderDetail1 = order.OrderDetails; //第一次访问,查询数据库 - var orderDetail2 = order.OrderDetails; //第二次访问,不查 - var order1 = orderDetail1.FirstOrDefault().Order; //访问导航属性,此时不查数据库,因为 OrderDetails 查询出来的时候已填充了该属性 - - - var queryable = g.mysql.Queryable().Where(a => a.Id == 1).ToList(); - - var sql2222 = select.Where(a => - select.Where(b => b.Id == a.Id && - select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) - //.Offset(a.Id) - .Any() - ).Any() - ).ToList(); - - - var groupbysql = g.mysql.Select().From((s, b, c) => s - .Where(a => a.Id == 1) - .WhereIf(false, a => a.Id == 2) - ) - .WhereIf(true, (a, b, c) => a.Id == 3) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()).ToSql(a => new { - cou = a.Sum(a.Value.Item1.Id), - a.Key.mod4, a.Key.tt2, max = a.Max("a.id"), max2 = Convert.ToInt64("max(a.id)") }); - - var groupbysql2 = g.mysql.Select().From((s, b, c) => s - .Where(a => a.Id == 1) - .WhereIf(true, a => a.Id == 2) - ) - .WhereIf(false, (a, b, c) => a.Id == 3) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()).ToSql(a => a.Key.mod4); - - var groupby = g.mysql.Select().From((s, b, c) => s - .Where(a => a.Id == 1) - .WhereIf(true, a => a.Id == 2) - ) - .WhereIf(true, (a,b,c) => a.Id == 3) - .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) - .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) - .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) - .OrderBy(a => a.Key.tt2) - .OrderByDescending(a => a.Count()) - .ToList(a => new { a.Key.tt2, cou1 = a.Count(), arg1 = a.Avg(a.Key.mod4), - ccc2 = a.Key.tt2 ?? "now()", - //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") - }); - - var arrg = g.mysql.Select().ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); - - var arrg222 = g.mysql.Select().ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); - - var t1 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - var t2 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - - - var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToList(); - var sql2 = select.LeftJoin((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToList(); - var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToList(); - - //g.mysql.Select().Join((a, b, c) => new Model.JoinResult3( - // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, - // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") - //); - - //var sql4 = select.From((a, b, c) => new SelectFrom() - // .InnerJoin(a.TypeGuid == b.Guid) - // .LeftJoin(c.Id == b.ParentId) - // .Where(b.Name == "xxx")) - //.Where(a => a.Id == 1).ToSql(); - - var sql4 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => c.Id == b.ParentId) - .Where(a => b.Name == "xxx")).ToList(); - //.Where(a => a.Id == 1).ToSql(); - - - var list111 = select.From((s, b, c) => s - .InnerJoin(a => a.TypeGuid == b.Guid) - .LeftJoin(a => c.Id == b.ParentId) - .Where(a => b.Name != "xxx")) - .ToList((a, b, c) => new { - a.Id, - a.Title, - a.Type, - ccc = new { a.Id, a.Title }, - tp = a.Type, - tp2 = new { - a.Id, - tp2 = a.Type.Name - }, - tp3 = new { - a.Id, - tp33 = new { - a.Id - } - } - }); - - var ttt122 = g.mysql.Select().Where(a => a.Id > 0).ToList(); - - - - - var sql5 = g.mysql.Select().From((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToList(); - - - - - - //((JoinType.LeftJoin, a.TypeGuid == b.Guid), (JoinType.InnerJoin, b.ParentId == c.Id) - - var t11112 = g.mysql.Select().ToList(a => new { - a.Id, a.Title, a.Type, - ccc = new { a.Id, a.Title }, - tp = a.Type, - tp2 = new { - a.Id, tp2 = a.Type.Name - }, - tp3 = new { - a.Id, - tp33 = new { - a.Id - } - } - - }); - - var t100 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - var t101 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); - - - var t1111 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type }); - - var t2222 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type.Name }); - - var t3 = g.mysql.Insert(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => a.Title).ToSql(); - var t4 = g.mysql.Insert(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); - var t5 = g.mysql.Insert(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => new { a.Title, a.TypeGuid, a.CreateTime }).ToSql(); - var t6 = g.mysql.Insert(new[] { new TestInfo { }, new TestInfo { } }).InsertColumns(a => new { a.Title }).ToSql(); - - var t7 = g.mysql.Update().ToSql(); - var t8 = g.mysql.Update().Where(new TestInfo { }).ToSql(); - var t9 = g.mysql.Update().Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); - var t10 = g.mysql.Update().Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); - var t11 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).ToSql(); - var t12 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Where(a => a.Title == "111").ToSql(); - - var t13 = g.mysql.Update().Set(a => a.Title, "222111").ToSql(); - var t14 = g.mysql.Update().Set(a => a.Title, "222111").Where(new TestInfo { }).ToSql(); - var t15 = g.mysql.Update().Set(a => a.Title, "222111").Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); - var t16 = g.mysql.Update().Set(a => a.Title, "222111").Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); - var t17 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.Title, "222111").ToSql(); - var t18 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.Title, "222111").Where(a => a.Title == "111").ToSql(); - - var t19 = g.mysql.Update().Set(a => a.TypeGuid + 222111).ToSql(); - var t20 = g.mysql.Update().Set(a => a.TypeGuid + 222111).Where(new TestInfo { }).ToSql(); - var t21 = g.mysql.Update().Set(a => a.TypeGuid + 222111).Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); - var t22 = g.mysql.Update().Set(a => a.TypeGuid + 222111).Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); - var t23 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.TypeGuid + 222111).ToSql(); - var t24 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.TypeGuid + 222111).Where(a => a.Title == "111").ToSql(); - - - var t1000 = g.sqlite.Select().ToSql(); - var t1001 = g.sqlite.Insert().AppendData(new ExamPaper()).ToSql(); - } - } - class NullAggreTestTable { - [Column(IsIdentity = true)] - public int Id { get; set; } - } - - - [Table(Name = "TestInfoT1", SelectFilter = " a.id > 0")] - class TestInfo { - [Column(IsIdentity = true, IsPrimary = true)] - public int Id { get; set; } - public int TypeGuid { get; set; } - public TestTypeInfo Type { get; set; } - public string Title { get; set; } - public DateTime CreateTime { get; set; } - } - - [Table(Name = "TestTypeInfoT1")] - class TestTypeInfo { - [Column(IsIdentity = true)] - public int Guid { get; set; } - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public string Name { get; set; } - } - - [Table(Name = "TestTypeParentInfoT1")] - class TestTypeParentInfo { - [Column(IsIdentity = true)] - public int Id { get; set; } - public string Name { get; set; } - - public int ParentId { get; set; } - public TestTypeParentInfo Parent { get; set; } - public ICollection Childs { get; set; } - - public List Types { get; set; } - } - - - /// - /// 试卷表 - /// - [Table(Name = "exam_paper")] - public class ExamPaper { - - public long id { get; set; } - - /// - /// 考核计划ID - /// - public long AssessmentPlanId { get; set; } - /// - /// 总分 - /// - public int TotalScore { get; set; } - - public DateTime BeginTime { get; set; } - - public DateTime? EndTime { get; set; } - - //[Column(IsIgnore = true)] - //public ExamStatus Status { get; set; } - public ExamStatus Status { - get { - if (DateTime.Now <= BeginTime) - return ExamStatus.Wait; - if (BeginTime <= DateTime.Now && (!EndTime.HasValue || DateTime.Now < EndTime)) - return ExamStatus.Started; - if (BeginTime <= DateTime.Now && (EndTime.HasValue && EndTime <= DateTime.Now)) - return ExamStatus.End; - return ExamStatus.Wait; - } - } - } - public enum ExamStatus { Wait, Started, End } + //var dic = Newtonsoft.Json.JsonConvert.DeserializeObject>(testjson); + var reqs = Newtonsoft.Json.JsonConvert.DeserializeObject>(testjson); + reqs.ForEach(t => + { + g.oracle.Insert(t).ExecuteAffrows(); + + }); + + + + var sql111 = g.sqlite.Select().AsTable((a, b) => "(select * from TestUser where stringid > 10)").Page(1, 10).ToSql(); + + + var xxx = g.sqlite.Select().GroupBy(a => new { a.stringid }).ToList(a => a.Key.stringid); + + var tuser = g.sqlite.Select().Where(u => u.accname == "admin") + .InnerJoin(a => a.LogOn.id == a.stringid).ToSql(); + + + var parentSelect1 = select.Where(a => a.Type.Parent.Parent.Parent.Parent.Name == "").Where(b => b.Type.Name == "").ToSql(); + + + var collSelect1 = g.mysql.Select().Where(a => + a.OrderDetails.AsSelect().Any(b => b.Id > 100) + ); + + var collectionSelect = select.Where(a => + //a.Type.Guid == a.TypeGuid && + //a.Type.Parent.Id == a.Type.ParentId && + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( + //b => b.ParentId == a.Type.Parent.Id + ) + ); + + var collectionSelect2 = select.Where(a => + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( + b => b.Parent.Name == "xxx" && b.Parent.Parent.Name == "ccc" + && b.Parent.Parent.Parent.Types.AsSelect().Any(cb => cb.Name == "yyy") + ) + ); + + var collectionSelect3 = select.Where(a => + a.Type.Parent.Types.AsSelect().Where(b => b.Name == a.Title).Any( + bbb => bbb.Parent.Types.AsSelect().Where(lv2 => lv2.Name == bbb.Name + "111").Any( + ) + ) + ); + + + var neworder = new Order + { + CustomerName = "testCustomer", + OrderTitle = "xxx#cccksksk", + TransactionDate = DateTime.Now, + OrderDetails = new List(new[] { + new OrderDetail { + + }, + new OrderDetail { + + } + }) + }; + + g.mysql.GetRepository().Insert(neworder); + + var order = g.mysql.Select().Where(a => a.Id == neworder.Id).ToOne(); //查询订单表 + if (order == null) + { + var orderId = g.mysql.Insert(new Order { }).ExecuteIdentity(); + order = g.mysql.Select(orderId).ToOne(); + } + + + var orderDetail1 = order.OrderDetails; //第一次访问,查询数据库 + var orderDetail2 = order.OrderDetails; //第二次访问,不查 + var order1 = orderDetail1.FirstOrDefault().Order; //访问导航属性,此时不查数据库,因为 OrderDetails 查询出来的时候已填充了该属性 + + + var queryable = g.mysql.Queryable().Where(a => a.Id == 1).ToList(); + + var sql2222 = select.Where(a => + select.Where(b => b.Id == a.Id && + select.Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id) + //.Offset(a.Id) + .Any() + ).Any() + ).ToList(); + + + var groupbysql = g.mysql.Select().From((s, b, c) => s + .Where(a => a.Id == 1) + .WhereIf(false, a => a.Id == 2) + ) + .WhereIf(true, (a, b, c) => a.Id == 3) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()).ToSql(a => new + { + cou = a.Sum(a.Value.Item1.Id), + a.Key.mod4, + a.Key.tt2, + max = a.Max("a.id"), + max2 = Convert.ToInt64("max(a.id)") + }); + + var groupbysql2 = g.mysql.Select().From((s, b, c) => s + .Where(a => a.Id == 1) + .WhereIf(true, a => a.Id == 2) + ) + .WhereIf(false, (a, b, c) => a.Id == 3) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()).ToSql(a => a.Key.mod4); + + var groupby = g.mysql.Select().From((s, b, c) => s + .Where(a => a.Id == 1) + .WhereIf(true, a => a.Id == 2) + ) + .WhereIf(true, (a, b, c) => a.Id == 3) + .GroupBy((a, b, c) => new { tt2 = a.Title.Substring(0, 2), mod4 = a.Id % 4 }) + .Having(a => a.Count() > 0 && a.Avg(a.Key.mod4) > 0 && a.Max(a.Key.mod4) > 0) + .Having(a => a.Count() < 300 || a.Avg(a.Key.mod4) < 100) + .OrderBy(a => a.Key.tt2) + .OrderByDescending(a => a.Count()) + .ToList(a => new + { + a.Key.tt2, + cou1 = a.Count(), + arg1 = a.Avg(a.Key.mod4), + ccc2 = a.Key.tt2 ?? "now()", + //ccc = Convert.ToDateTime("now()"), partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") + }); + + var arrg = g.mysql.Select().ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); + + var arrg222 = g.mysql.Select().ToAggregate(a => new { sum = a.Sum(a.Key.Id + 11.11), avg = a.Avg(a.Key.Id), count = a.Count(), max = a.Max(a.Key.Id), min = a.Min(a.Key.Id) }); + + var t1 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + var t2 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + + + var sql1 = select.LeftJoin(a => a.Type.Guid == a.TypeGuid).ToList(); + var sql2 = select.LeftJoin((a, b) => a.TypeGuid == b.Guid && b.Name == "111").ToList(); + var sql3 = select.LeftJoin("TestTypeInfo b on b.Guid = a.TypeGuid").ToList(); + + //g.mysql.Select().Join((a, b, c) => new Model.JoinResult3( + // Model.JoinType.LeftJoin, a.TypeGuid == b.Guid, + // Model.JoinType.InnerJoin, c.Id == b.ParentId && c.Name == "xxx") + //); + + //var sql4 = select.From((a, b, c) => new SelectFrom() + // .InnerJoin(a.TypeGuid == b.Guid) + // .LeftJoin(c.Id == b.ParentId) + // .Where(b.Name == "xxx")) + //.Where(a => a.Id == 1).ToSql(); + + var sql4 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => c.Id == b.ParentId) + .Where(a => b.Name == "xxx")).ToList(); + //.Where(a => a.Id == 1).ToSql(); + + + var list111 = select.From((s, b, c) => s + .InnerJoin(a => a.TypeGuid == b.Guid) + .LeftJoin(a => c.Id == b.ParentId) + .Where(a => b.Name != "xxx")) + .ToList((a, b, c) => new + { + a.Id, + a.Title, + a.Type, + ccc = new { a.Id, a.Title }, + tp = a.Type, + tp2 = new + { + a.Id, + tp2 = a.Type.Name + }, + tp3 = new + { + a.Id, + tp33 = new + { + a.Id + } + } + }); + + var ttt122 = g.mysql.Select().Where(a => a.Id > 0).ToList(); + + + + + var sql5 = g.mysql.Select().From((s, b, c) => s).Where((a, b, c) => a.Id == b.ParentId).ToList(); + + + + + + //((JoinType.LeftJoin, a.TypeGuid == b.Guid), (JoinType.InnerJoin, b.ParentId == c.Id) + + var t11112 = g.mysql.Select().ToList(a => new + { + a.Id, + a.Title, + a.Type, + ccc = new { a.Id, a.Title }, + tp = a.Type, + tp2 = new + { + a.Id, + tp2 = a.Type.Name + }, + tp3 = new + { + a.Id, + tp33 = new + { + a.Id + } + } + + }); + + var t100 = g.mysql.Select().Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + var t101 = g.mysql.Select().As("b").Where("").Where(a => a.Id > 0).Skip(100).Limit(200).ToList(); + + + var t1111 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type }); + + var t2222 = g.mysql.Select().ToList(a => new { a.Id, a.Title, a.Type.Name }); + + var t3 = g.mysql.Insert(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => a.Title).ToSql(); + var t4 = g.mysql.Insert(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => new { a.Title, a.CreateTime }).ToSql(); + var t5 = g.mysql.Insert(new[] { new TestInfo { }, new TestInfo { } }).IgnoreColumns(a => new { a.Title, a.TypeGuid, a.CreateTime }).ToSql(); + var t6 = g.mysql.Insert(new[] { new TestInfo { }, new TestInfo { } }).InsertColumns(a => new { a.Title }).ToSql(); + + var t7 = g.mysql.Update().ToSql(); + var t8 = g.mysql.Update().Where(new TestInfo { }).ToSql(); + var t9 = g.mysql.Update().Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); + var t10 = g.mysql.Update().Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); + var t11 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).ToSql(); + var t12 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Where(a => a.Title == "111").ToSql(); + + var t13 = g.mysql.Update().Set(a => a.Title, "222111").ToSql(); + var t14 = g.mysql.Update().Set(a => a.Title, "222111").Where(new TestInfo { }).ToSql(); + var t15 = g.mysql.Update().Set(a => a.Title, "222111").Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); + var t16 = g.mysql.Update().Set(a => a.Title, "222111").Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); + var t17 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.Title, "222111").ToSql(); + var t18 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.Title, "222111").Where(a => a.Title == "111").ToSql(); + + var t19 = g.mysql.Update().Set(a => a.TypeGuid + 222111).ToSql(); + var t20 = g.mysql.Update().Set(a => a.TypeGuid + 222111).Where(new TestInfo { }).ToSql(); + var t21 = g.mysql.Update().Set(a => a.TypeGuid + 222111).Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).ToSql(); + var t22 = g.mysql.Update().Set(a => a.TypeGuid + 222111).Where(new[] { new TestInfo { Id = 1 }, new TestInfo { Id = 2 } }).Where(a => a.Title == "111").ToSql(); + var t23 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.TypeGuid + 222111).ToSql(); + var t24 = g.mysql.Update().SetSource(new[] { new TestInfo { Id = 1, Title = "111" }, new TestInfo { Id = 2, Title = "222" } }).Set(a => a.TypeGuid + 222111).Where(a => a.Title == "111").ToSql(); + + + var t1000 = g.sqlite.Select().ToSql(); + var t1001 = g.sqlite.Insert().AppendData(new ExamPaper()).ToSql(); + } + } + class NullAggreTestTable + { + [Column(IsIdentity = true)] + public int Id { get; set; } + } + + + [Table(Name = "TestInfoT1", SelectFilter = " a.id > 0")] + class TestInfo + { + [Column(IsIdentity = true, IsPrimary = true)] + public int Id { get; set; } + public int TypeGuid { get; set; } + public TestTypeInfo Type { get; set; } + public string Title { get; set; } + public DateTime CreateTime { get; set; } + } + + [Table(Name = "TestTypeInfoT1")] + class TestTypeInfo + { + [Column(IsIdentity = true)] + public int Guid { get; set; } + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public string Name { get; set; } + } + + [Table(Name = "TestTypeParentInfoT1")] + class TestTypeParentInfo + { + [Column(IsIdentity = true)] + public int Id { get; set; } + public string Name { get; set; } + + public int ParentId { get; set; } + public TestTypeParentInfo Parent { get; set; } + public ICollection Childs { get; set; } + + public List Types { get; set; } + } + + + /// + /// 试卷表 + /// + [Table(Name = "exam_paper")] + public class ExamPaper + { + + public long id { get; set; } + + /// + /// 考核计划ID + /// + public long AssessmentPlanId { get; set; } + /// + /// 总分 + /// + public int TotalScore { get; set; } + + public DateTime BeginTime { get; set; } + + public DateTime? EndTime { get; set; } + + //[Column(IsIgnore = true)] + //public ExamStatus Status { get; set; } + public ExamStatus Status + { + get + { + if (DateTime.Now <= BeginTime) + return ExamStatus.Wait; + if (BeginTime <= DateTime.Now && (!EndTime.HasValue || DateTime.Now < EndTime)) + return ExamStatus.Started; + if (BeginTime <= DateTime.Now && (EndTime.HasValue && EndTime <= DateTime.Now)) + return ExamStatus.End; + return ExamStatus.Wait; + } + } + } + public enum ExamStatus { Wait, Started, End } } diff --git a/FreeSql.Tests/FreeSql.Tests/UnitTest2.cs b/FreeSql.Tests/FreeSql.Tests/UnitTest2.cs index 1b1b056a..5234ee72 100644 --- a/FreeSql.Tests/FreeSql.Tests/UnitTest2.cs +++ b/FreeSql.Tests/FreeSql.Tests/UnitTest2.cs @@ -11,10 +11,13 @@ using System.Linq.Expressions; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; -namespace FreeSql.Tests { - public class UnitTest2 { +namespace FreeSql.Tests +{ + public class UnitTest2 + { - public partial class SysModulePermission { + public partial class SysModulePermission + { /// /// 菜单权限ID /// @@ -35,7 +38,8 @@ namespace FreeSql.Tests { /// public Int32 Status { get; set; } } - public partial class SysModule { + public partial class SysModule + { /// /// 主键 /// @@ -83,7 +87,8 @@ namespace FreeSql.Tests { public DateTime CreateTime { get; set; } } - public partial class SysModuleButton { + public partial class SysModuleButton + { /// /// 按钮主键 /// @@ -120,17 +125,21 @@ namespace FreeSql.Tests { /// public DateTime CreateTime { get; set; } } - partial class SysModulePermission { + partial class SysModulePermission + { public SysModuleButton Button { get; set; } } - partial class SysModule { + partial class SysModule + { public List Permissions { get; set; } } - partial class SysModuleButton { + partial class SysModuleButton + { } [Fact] - public void Test02() { + public void Test02() + { g.sqlite.Delete().Where("1=1").ExecuteAffrows(); g.sqlite.Delete().Where("1=1").ExecuteAffrows(); @@ -164,7 +173,7 @@ namespace FreeSql.Tests { // .ToList(); var list = g.sqlite.Select() - .IncludeMany(m => m.Permissions.Where(p => p.SysModuleId == m.SysModuleId), + .IncludeMany(m => m.Permissions.Where(p => p.SysModuleId == m.SysModuleId), then => then.LeftJoin(p => p.Button.SysModuleButtonId == p.SysModuleButtonId)) .ToList(); } diff --git a/FreeSql.Tests/FreeSql.Tests/g.cs b/FreeSql.Tests/FreeSql.Tests/g.cs index 7396b139..037e941f 100644 --- a/FreeSql.Tests/FreeSql.Tests/g.cs +++ b/FreeSql.Tests/FreeSql.Tests/g.cs @@ -5,82 +5,94 @@ using System.Diagnostics; using System.Text; -public class g { +public class g +{ - static Lazy mysqlLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10") - .UseAutoSyncStructure(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .UseLazyLoading(true) - .Build()); - public static IFreeSql mysql => mysqlLazy.Value; + static Lazy mysqlLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10") + .UseAutoSyncStructure(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .UseLazyLoading(true) + .Build()); + public static IFreeSql mysql => mysqlLazy.Value; - static Lazy pgsqlLazy = new Lazy(() => { - NpgsqlConnection.GlobalTypeMapper.UseLegacyPostgis(); - return new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10") - .UseAutoSyncStructure(true) - .UseSyncStructureToLower(true) - .UseLazyLoading(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .Build(); - }); - public static IFreeSql pgsql => pgsqlLazy.Value; + static Lazy pgsqlLazy = new Lazy(() => + { + NpgsqlConnection.GlobalTypeMapper.UseLegacyPostgis(); + return new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.PostgreSQL, "Host=192.168.164.10;Port=5432;Username=postgres;Password=123456;Database=tedb;Pooling=true;Maximum Pool Size=10") + .UseAutoSyncStructure(true) + .UseSyncStructureToLower(true) + .UseLazyLoading(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .Build(); + }); + public static IFreeSql pgsql => pgsqlLazy.Value; - static Lazy sqlserverLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .UseLazyLoading(true) - .Build()); - public static IFreeSql sqlserver => sqlserverLazy.Value; + static Lazy sqlserverLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=freesqlTest;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .UseLazyLoading(true) + .Build()); + public static IFreeSql sqlserver => sqlserverLazy.Value; - static Lazy oracleLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseLazyLoading(true) - .UseSyncStructureToUpper(true) - //.UseNoneCommandParameter(true) + static Lazy oracleLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Oracle, "user id=user1;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseLazyLoading(true) + .UseSyncStructureToUpper(true) + //.UseNoneCommandParameter(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .Build()); - public static IFreeSql oracle => oracleLazy.Value; + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .Build()); + public static IFreeSql oracle => oracleLazy.Value; - static Lazy sqliteLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10") - .UseAutoSyncStructure(true) - .UseLazyLoading(true) - .UseMonitorCommand( - cmd => { - Trace.WriteLine(cmd.CommandText); - }, //监听SQL命令对象,在执行前 - (cmd, traceLog) => { - Console.WriteLine(traceLog); - }) //监听SQL命令对象,在执行后 - .Build()); - public static IFreeSql sqlite => sqliteLazy.Value; + static Lazy sqliteLazy = new Lazy(() => new FreeSql.FreeSqlBuilder() + .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=10") + .UseAutoSyncStructure(true) + .UseLazyLoading(true) + .UseMonitorCommand( + cmd => + { + Trace.WriteLine(cmd.CommandText); + }, //监听SQL命令对象,在执行前 + (cmd, traceLog) => + { + Console.WriteLine(traceLog); + }) //监听SQL命令对象,在执行后 + .Build()); + public static IFreeSql sqlite => sqliteLazy.Value; } diff --git a/FreeSql/DataAnnotations/ColumnAttribute.cs b/FreeSql/DataAnnotations/ColumnAttribute.cs index 412b3bde..dc2300e2 100644 --- a/FreeSql/DataAnnotations/ColumnAttribute.cs +++ b/FreeSql/DataAnnotations/ColumnAttribute.cs @@ -1,76 +1,83 @@ using System; using System.Linq; -namespace FreeSql.DataAnnotations { - public class ColumnAttribute : Attribute { +namespace FreeSql.DataAnnotations +{ + public class ColumnAttribute : Attribute + { - /// - /// 数据库列名 - /// - public string Name { get; set; } - /// - /// 指定数据库旧的列名,修改实体属性命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库字段;否则将视为【新增字段】 - /// - public string OldName { get; set; } - /// - /// 数据库类型,如: varchar(255) - /// - public string DbType { get; set; } + /// + /// 数据库列名 + /// + public string Name { get; set; } + /// + /// 指定数据库旧的列名,修改实体属性命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库字段;否则将视为【新增字段】 + /// + public string OldName { get; set; } + /// + /// 数据库类型,如: varchar(255) + /// + public string DbType { get; set; } - internal bool? _IsPrimary, _IsIdentity, _IsNullable, _IsIgnore, _IsVersion; - /// - /// 主键 - /// - public bool IsPrimary { get => _IsPrimary ?? false; set => _IsPrimary = value; } - /// - /// 自增标识 - /// - public bool IsIdentity { get => _IsIdentity ?? false; set => _IsIdentity = value; } - /// - /// 是否可DBNull - /// - public bool IsNullable { get => _IsNullable ?? false; set => _IsNullable = value; } - /// - /// 忽略此列,不迁移、不插入 - /// - public bool IsIgnore { get => _IsIgnore ?? false; set => _IsIgnore = value; } - /// - /// 设置行锁(乐观锁)版本号,每次更新累加版本号,若更新整个实体时会附带当前的版本号判断(修改失败时抛出异常) - /// - public bool IsVersion { get => _IsVersion ?? false; set => _IsVersion = value; } + internal bool? _IsPrimary, _IsIdentity, _IsNullable, _IsIgnore, _IsVersion; + /// + /// 主键 + /// + public bool IsPrimary { get => _IsPrimary ?? false; set => _IsPrimary = value; } + /// + /// 自增标识 + /// + public bool IsIdentity { get => _IsIdentity ?? false; set => _IsIdentity = value; } + /// + /// 是否可DBNull + /// + public bool IsNullable { get => _IsNullable ?? false; set => _IsNullable = value; } + /// + /// 忽略此列,不迁移、不插入 + /// + public bool IsIgnore { get => _IsIgnore ?? false; set => _IsIgnore = value; } + /// + /// 设置行锁(乐观锁)版本号,每次更新累加版本号,若更新整个实体时会附带当前的版本号判断(修改失败时抛出异常) + /// + public bool IsVersion { get => _IsVersion ?? false; set => _IsVersion = value; } - internal string[] _Uniques; - /// - /// 唯一键,在多个属性指定相同的标识,代表联合键;可使用逗号分割多个 UniqueKey 名。 - /// - public string Unique { - get => _Uniques == null ? null : string.Join(", ", _Uniques); - set { - if (string.IsNullOrEmpty(value)) { - _Uniques = null; - return; - } - var val = value?.Trim(' ', '\t', ','); - if (string.IsNullOrEmpty(val)) { - _Uniques = null; - return; - } - var arr = val.Split(',').Select(a => a.Trim(' ', '\t').Trim()).Where(a => !string.IsNullOrEmpty(a)).ToArray(); - if (arr.Any() == false) { - _Uniques = null; - return; - } - _Uniques = arr; - } - } - /// - /// 数据库默认值 - /// - public object DbDefautValue { get; internal set; } + internal string[] _Uniques; + /// + /// 唯一键,在多个属性指定相同的标识,代表联合键;可使用逗号分割多个 UniqueKey 名。 + /// + public string Unique + { + get => _Uniques == null ? null : string.Join(", ", _Uniques); + set + { + if (string.IsNullOrEmpty(value)) + { + _Uniques = null; + return; + } + var val = value?.Trim(' ', '\t', ','); + if (string.IsNullOrEmpty(val)) + { + _Uniques = null; + return; + } + var arr = val.Split(',').Select(a => a.Trim(' ', '\t').Trim()).Where(a => !string.IsNullOrEmpty(a)).ToArray(); + if (arr.Any() == false) + { + _Uniques = null; + return; + } + _Uniques = arr; + } + } + /// + /// 数据库默认值 + /// + public object DbDefautValue { get; internal set; } - /// - /// 类型映射,比如:可将 enum 属性映射成 typeof(string) - /// - public Type MapType { get; set; } - } + /// + /// 类型映射,比如:可将 enum 属性映射成 typeof(string) + /// + public Type MapType { get; set; } + } } diff --git a/FreeSql/DataAnnotations/ColumnFluent.cs b/FreeSql/DataAnnotations/ColumnFluent.cs index 6894cde1..67b3d885 100644 --- a/FreeSql/DataAnnotations/ColumnFluent.cs +++ b/FreeSql/DataAnnotations/ColumnFluent.cs @@ -1,87 +1,100 @@ using System; -namespace FreeSql.DataAnnotations { - public class ColumnFluent { +namespace FreeSql.DataAnnotations +{ + public class ColumnFluent + { - public ColumnFluent(ColumnAttribute column) { - _column = column; - } + public ColumnFluent(ColumnAttribute column) + { + _column = column; + } - ColumnAttribute _column; - /// - /// 数据库列名 - /// - public ColumnFluent Name(string value) { - _column.Name = value; - return this; - } - /// - /// 指定数据库旧的列名,修改实体属性命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库字段;否则将视为【新增字段】 - /// - public ColumnFluent OldName(string value) { - _column.OldName = value; - return this; - } - /// - /// 数据库类型,如: varchar(255) - /// - public ColumnFluent DbType(string value) { - _column.DbType = value; - return this; - } + ColumnAttribute _column; + /// + /// 数据库列名 + /// + public ColumnFluent Name(string value) + { + _column.Name = value; + return this; + } + /// + /// 指定数据库旧的列名,修改实体属性命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库字段;否则将视为【新增字段】 + /// + public ColumnFluent OldName(string value) + { + _column.OldName = value; + return this; + } + /// + /// 数据库类型,如: varchar(255) + /// + public ColumnFluent DbType(string value) + { + _column.DbType = value; + return this; + } - /// - /// 主键 - /// - public ColumnFluent IsPrimary(bool value) { - _column.IsPrimary = value; - return this; - } - /// - /// 自增标识 - /// - public ColumnFluent IsIdentity(bool value) { - _column.IsIdentity = value; - return this; - } - /// - /// 是否可DBNull - /// - public ColumnFluent IsNullable(bool value) { - _column.IsNullable = value; - return this; - } - /// - /// 忽略此列,不迁移、不插入 - /// - public ColumnFluent IsIgnore(bool value) { - _column.IsIgnore = value; - return this; - } - /// - /// 乐观锁 - /// - public ColumnFluent IsVersion(bool value) { - _column.IsVersion = value; - return this; - } - /// - /// 唯一键,在多个属性指定相同的标识,代表联合键;可使用逗号分割多个 UniqueKey 名。 - /// - /// 标识 - /// - public ColumnFluent Unique(string value) { - _column.Unique = value; - return this; - } - /// - /// 类型映射,比如:可将 enum 属性映射成 typeof(string) - /// - /// - /// - public ColumnFluent MapType(Type type) { - _column.MapType = type; - return this; - } - } + /// + /// 主键 + /// + public ColumnFluent IsPrimary(bool value) + { + _column.IsPrimary = value; + return this; + } + /// + /// 自增标识 + /// + public ColumnFluent IsIdentity(bool value) + { + _column.IsIdentity = value; + return this; + } + /// + /// 是否可DBNull + /// + public ColumnFluent IsNullable(bool value) + { + _column.IsNullable = value; + return this; + } + /// + /// 忽略此列,不迁移、不插入 + /// + public ColumnFluent IsIgnore(bool value) + { + _column.IsIgnore = value; + return this; + } + /// + /// 乐观锁 + /// + public ColumnFluent IsVersion(bool value) + { + _column.IsVersion = value; + return this; + } + /// + /// 唯一键,在多个属性指定相同的标识,代表联合键;可使用逗号分割多个 UniqueKey 名。 + /// + /// 标识 + /// + public ColumnFluent Unique(string value) + { + _column.Unique = value; + return this; + } + /// + /// 类型映射,比如:可将 enum 属性映射成 typeof(string) + /// + /// + /// + public ColumnFluent MapType(Type type) + { + _column.MapType = type; + return this; + } + } } diff --git a/FreeSql/DataAnnotations/NavigateAttribute.cs b/FreeSql/DataAnnotations/NavigateAttribute.cs index d9b052f5..d908a627 100644 --- a/FreeSql/DataAnnotations/NavigateAttribute.cs +++ b/FreeSql/DataAnnotations/NavigateAttribute.cs @@ -1,16 +1,19 @@ using System; using System.Linq; -namespace FreeSql.DataAnnotations { - public class NavigateAttribute : Attribute { +namespace FreeSql.DataAnnotations +{ + public class NavigateAttribute : Attribute + { - /// - /// 导航属性,手工绑定 - /// - public string Bind { get; set; } + /// + /// 导航属性,手工绑定 + /// + public string Bind { get; set; } - public NavigateAttribute(string bind) { - this.Bind = bind; - } - } + public NavigateAttribute(string bind) + { + this.Bind = bind; + } + } } diff --git a/FreeSql/DataAnnotations/TableAttribute.cs b/FreeSql/DataAnnotations/TableAttribute.cs index c1061e93..b70858b4 100644 --- a/FreeSql/DataAnnotations/TableAttribute.cs +++ b/FreeSql/DataAnnotations/TableAttribute.cs @@ -1,28 +1,30 @@ using System; using System.Collections.Concurrent; -namespace FreeSql.DataAnnotations { - public class TableAttribute : Attribute { +namespace FreeSql.DataAnnotations +{ + public class TableAttribute : Attribute + { - /// - /// 数据库表名 - /// - public string Name { get; set; } - /// - /// 指定数据库旧的表名,修改实体命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库表;否则将视为【创建新表】 - /// - public string OldName { get; set; } - /// - /// 查询过滤SQL,实现类似 a.IsDeleted = 1 功能 - /// - public string SelectFilter { get; set; } + /// + /// 数据库表名 + /// + public string Name { get; set; } + /// + /// 指定数据库旧的表名,修改实体命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库表;否则将视为【创建新表】 + /// + public string OldName { get; set; } + /// + /// 查询过滤SQL,实现类似 a.IsDeleted = 1 功能 + /// + public string SelectFilter { get; set; } - internal bool? _DisableSyncStructure; - /// - /// 禁用 CodeFirst 同步结构迁移 - /// - public bool DisableSyncStructure { get => _DisableSyncStructure ?? false; set => _DisableSyncStructure = value; } + internal bool? _DisableSyncStructure; + /// + /// 禁用 CodeFirst 同步结构迁移 + /// + public bool DisableSyncStructure { get => _DisableSyncStructure ?? false; set => _DisableSyncStructure = value; } - internal ConcurrentDictionary _columns { get; } = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - } + internal ConcurrentDictionary _columns { get; } = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + } } diff --git a/FreeSql/DataAnnotations/TableFluent.cs b/FreeSql/DataAnnotations/TableFluent.cs index 64383cd4..0e6d1155 100644 --- a/FreeSql/DataAnnotations/TableFluent.cs +++ b/FreeSql/DataAnnotations/TableFluent.cs @@ -4,97 +4,112 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; -namespace FreeSql.DataAnnotations { - public class TableFluent { +namespace FreeSql.DataAnnotations +{ + public class TableFluent + { - public TableFluent(Type entityType, TableAttribute table) { - _entityType = entityType; - _properties = _entityType.GetProperties().ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase); - _table = table; - } + public TableFluent(Type entityType, TableAttribute table) + { + _entityType = entityType; + _properties = _entityType.GetProperties().ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase); + _table = table; + } - Type _entityType; - Dictionary _properties; - TableAttribute _table; - /// - /// 数据库表名 - /// - public TableFluent Name(string value) { - _table.Name = value; - return this; - } - /// - /// 指定数据库旧的表名,修改实体命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库表;否则将视为【创建新表】 - /// - public TableFluent OldName(string value) { - _table.OldName = value; - return this; - } - /// - /// 查询过滤SQL,实现类似 a.IsDeleted = 1 功能 - /// - public TableFluent SelectFilter(string value) { - _table.SelectFilter = value; - return this; - } + Type _entityType; + Dictionary _properties; + TableAttribute _table; + /// + /// 数据库表名 + /// + public TableFluent Name(string value) + { + _table.Name = value; + return this; + } + /// + /// 指定数据库旧的表名,修改实体命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库表;否则将视为【创建新表】 + /// + public TableFluent OldName(string value) + { + _table.OldName = value; + return this; + } + /// + /// 查询过滤SQL,实现类似 a.IsDeleted = 1 功能 + /// + public TableFluent SelectFilter(string value) + { + _table.SelectFilter = value; + return this; + } - /// - /// 禁用 CodeFirst 同步结构迁移 - /// - public TableFluent DisableSyncStructure(bool value) { - _table.DisableSyncStructure = value; - return this; - } + /// + /// 禁用 CodeFirst 同步结构迁移 + /// + public TableFluent DisableSyncStructure(bool value) + { + _table.DisableSyncStructure = value; + return this; + } - public ColumnFluent Property(string proto) { - if (_properties.ContainsKey(proto) == false) throw new KeyNotFoundException($"找不到属性名 {proto}"); - var col = _table._columns.GetOrAdd(proto, name => new ColumnAttribute { Name = proto }); - return new ColumnFluent(col); - } - } + public ColumnFluent Property(string proto) + { + if (_properties.ContainsKey(proto) == false) throw new KeyNotFoundException($"找不到属性名 {proto}"); + var col = _table._columns.GetOrAdd(proto, name => new ColumnAttribute { Name = proto }); + return new ColumnFluent(col); + } + } - public class TableFluent { + public class TableFluent + { - public TableFluent(TableAttribute table) { - _table = table; - } + public TableFluent(TableAttribute table) + { + _table = table; + } - TableAttribute _table; - /// - /// 数据库表名 - /// - public TableFluent Name(string value) { - _table.Name = value; - return this; - } - /// - /// 指定数据库旧的表名,修改实体命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库表;否则将视为【创建新表】 - /// - public TableFluent OldName(string value) { - _table.OldName = value; - return this; - } - /// - /// 查询过滤SQL,实现类似 a.IsDeleted = 1 功能 - /// - public TableFluent SelectFilter(string value) { - _table.SelectFilter = value; - return this; - } + TableAttribute _table; + /// + /// 数据库表名 + /// + public TableFluent Name(string value) + { + _table.Name = value; + return this; + } + /// + /// 指定数据库旧的表名,修改实体命名时,同时设置此参数为修改之前的值,CodeFirst才可以正确修改数据库表;否则将视为【创建新表】 + /// + public TableFluent OldName(string value) + { + _table.OldName = value; + return this; + } + /// + /// 查询过滤SQL,实现类似 a.IsDeleted = 1 功能 + /// + public TableFluent SelectFilter(string value) + { + _table.SelectFilter = value; + return this; + } - /// - /// 禁用 CodeFirst 同步结构迁移 - /// - public TableFluent DisableSyncStructure(bool value) { - _table.DisableSyncStructure = value; - return this; - } + /// + /// 禁用 CodeFirst 同步结构迁移 + /// + public TableFluent DisableSyncStructure(bool value) + { + _table.DisableSyncStructure = value; + return this; + } - public ColumnFluent Property(Expression> column) { - var proto = (column.Body as MemberExpression)?.Member; - if (proto == null) throw new FormatException($"错误的表达式格式 {column}"); - var col = _table._columns.GetOrAdd(proto.Name, name => new ColumnAttribute { Name = proto.Name }); - return new ColumnFluent(col); - } - } + public ColumnFluent Property(Expression> column) + { + var proto = (column.Body as MemberExpression)?.Member; + if (proto == null) throw new FormatException($"错误的表达式格式 {column}"); + var col = _table._columns.GetOrAdd(proto.Name, name => new ColumnAttribute { Name = proto.Name }); + return new ColumnFluent(col); + } + } } diff --git a/FreeSql/DataType.cs b/FreeSql/DataType.cs index 12ec3c06..32a769f3 100644 --- a/FreeSql/DataType.cs +++ b/FreeSql/DataType.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Text; -namespace FreeSql { - public enum DataType { MySql, SqlServer, PostgreSQL, Oracle, Sqlite } +namespace FreeSql +{ + public enum DataType { MySql, SqlServer, PostgreSQL, Oracle, Sqlite } } diff --git a/FreeSql/DatabaseModel/DBColumnInfo.cs b/FreeSql/DatabaseModel/DBColumnInfo.cs index 2fd9f6af..4ede12b5 100644 --- a/FreeSql/DatabaseModel/DBColumnInfo.cs +++ b/FreeSql/DatabaseModel/DBColumnInfo.cs @@ -1,50 +1,52 @@ using System; -namespace FreeSql.DatabaseModel { - public class DbColumnInfo { - /// - /// 所属表 - /// - public DbTableInfo Table { get; set; } - /// - /// 列名 - /// - public string Name { get; set; } - /// - /// 映射到 C# 类型 - /// - public Type CsType { get; set; } - /// - /// 数据库枚举类型int值 - /// - public int DbType { get; set; } - /// - /// 数据库类型,字符串,varchar - /// - public string DbTypeText { get; set; } - /// - /// 数据库类型,字符串,varchar(255) - /// - public string DbTypeTextFull { get; set; } - /// - /// 最大长度 - /// - public int MaxLength { get; set; } - /// - /// 主键 - /// - public bool IsPrimary { get; set; } - /// - /// 自增标识 - /// - public bool IsIdentity { get; set; } - /// - /// 是否可DBNull - /// - public bool IsNullable { get; set; } - /// - /// 备注 - /// - public string Coment { get; set; } - } +namespace FreeSql.DatabaseModel +{ + public class DbColumnInfo + { + /// + /// 所属表 + /// + public DbTableInfo Table { get; set; } + /// + /// 列名 + /// + public string Name { get; set; } + /// + /// 映射到 C# 类型 + /// + public Type CsType { get; set; } + /// + /// 数据库枚举类型int值 + /// + public int DbType { get; set; } + /// + /// 数据库类型,字符串,varchar + /// + public string DbTypeText { get; set; } + /// + /// 数据库类型,字符串,varchar(255) + /// + public string DbTypeTextFull { get; set; } + /// + /// 最大长度 + /// + public int MaxLength { get; set; } + /// + /// 主键 + /// + public bool IsPrimary { get; set; } + /// + /// 自增标识 + /// + public bool IsIdentity { get; set; } + /// + /// 是否可DBNull + /// + public bool IsNullable { get; set; } + /// + /// 备注 + /// + public string Coment { get; set; } + } } diff --git a/FreeSql/DatabaseModel/DBTableInfo.cs b/FreeSql/DatabaseModel/DBTableInfo.cs index 01a602f6..10dc42e0 100644 --- a/FreeSql/DatabaseModel/DBTableInfo.cs +++ b/FreeSql/DatabaseModel/DBTableInfo.cs @@ -1,59 +1,62 @@ using System.Collections.Generic; using System.Linq; -namespace FreeSql.DatabaseModel { - public class DbTableInfo { - /// - /// 唯一标识 - /// - public string Id { get; set; } - /// - /// SqlServer下是Owner、PostgreSQL下是Schema、MySql下是数据库名 - /// - public string Schema { get; set; } - /// - /// 表名 - /// - public string Name { get; set; } - /// - /// 表备注,SqlServer下是扩展属性 MS_Description - /// - public string Comment { get; set; } - /// - /// 表/视图 - /// - public DbTableType Type { get; set; } - /// - /// 列 - /// - public List Columns { get; set; } = new List(); - /// - /// 自增列 - /// - public List Identitys { get; set; } = new List(); - /// - /// 主键/组合 - /// - public List Primarys { get; set; } = new List(); - /// - /// 唯一键/组合 - /// - public Dictionary> UniquesDict { get; set; } = new Dictionary>(); - /// - /// 索引/组合 - /// - public Dictionary> IndexesDict { get; set; } = new Dictionary>(); - /// - /// 外键 - /// - public Dictionary ForeignsDict { get; set; } = new Dictionary(); +namespace FreeSql.DatabaseModel +{ + public class DbTableInfo + { + /// + /// 唯一标识 + /// + public string Id { get; set; } + /// + /// SqlServer下是Owner、PostgreSQL下是Schema、MySql下是数据库名 + /// + public string Schema { get; set; } + /// + /// 表名 + /// + public string Name { get; set; } + /// + /// 表备注,SqlServer下是扩展属性 MS_Description + /// + public string Comment { get; set; } + /// + /// 表/视图 + /// + public DbTableType Type { get; set; } + /// + /// 列 + /// + public List Columns { get; set; } = new List(); + /// + /// 自增列 + /// + public List Identitys { get; set; } = new List(); + /// + /// 主键/组合 + /// + public List Primarys { get; set; } = new List(); + /// + /// 唯一键/组合 + /// + public Dictionary> UniquesDict { get; set; } = new Dictionary>(); + /// + /// 索引/组合 + /// + public Dictionary> IndexesDict { get; set; } = new Dictionary>(); + /// + /// 外键 + /// + public Dictionary ForeignsDict { get; set; } = new Dictionary(); - public List> Uniques => UniquesDict.Values.ToList(); - public List> Indexes => IndexesDict.Values.ToList(); - public List Foreigns => ForeignsDict.Values.ToList(); - } + public List> Uniques => UniquesDict.Values.ToList(); + public List> Indexes => IndexesDict.Values.ToList(); + public List Foreigns => ForeignsDict.Values.ToList(); + } - public enum DbTableType { - TABLE, VIEW, StoreProcedure - } + public enum DbTableType + { + TABLE, VIEW, StoreProcedure + } } diff --git a/FreeSql/DatabaseModel/DbEnumInfo.cs b/FreeSql/DatabaseModel/DbEnumInfo.cs index 93638af0..b3eb30a4 100644 --- a/FreeSql/DatabaseModel/DbEnumInfo.cs +++ b/FreeSql/DatabaseModel/DbEnumInfo.cs @@ -1,16 +1,18 @@ using System.Collections.Generic; -namespace FreeSql.DatabaseModel { - public class DbEnumInfo { +namespace FreeSql.DatabaseModel +{ + public class DbEnumInfo + { - /// - /// 枚举类型标识 - /// - public string Name { get; set; } + /// + /// 枚举类型标识 + /// + public string Name { get; set; } - /// - /// 枚举项 - /// - public Dictionary Labels { get; set; } - } + /// + /// 枚举项 + /// + public Dictionary Labels { get; set; } + } } diff --git a/FreeSql/DatabaseModel/DbForeignInfo.cs b/FreeSql/DatabaseModel/DbForeignInfo.cs index 70dca1f5..b4a86c8f 100644 --- a/FreeSql/DatabaseModel/DbForeignInfo.cs +++ b/FreeSql/DatabaseModel/DbForeignInfo.cs @@ -1,11 +1,13 @@ using System.Collections.Generic; -namespace FreeSql.DatabaseModel { - public class DbForeignInfo { - public DbTableInfo Table { get; set; } - public List Columns { get; set; } = new List(); - public DbTableInfo ReferencedTable { get; set; } - public List ReferencedColumns { get; set; } = new List(); +namespace FreeSql.DatabaseModel +{ + public class DbForeignInfo + { + public DbTableInfo Table { get; set; } + public List Columns { get; set; } = new List(); + public DbTableInfo ReferencedTable { get; set; } + public List ReferencedColumns { get; set; } = new List(); - } + } } diff --git a/FreeSql/DatabaseModel/DbTypeInfo.cs b/FreeSql/DatabaseModel/DbTypeInfo.cs index 425a8821..eb319c02 100644 --- a/FreeSql/DatabaseModel/DbTypeInfo.cs +++ b/FreeSql/DatabaseModel/DbTypeInfo.cs @@ -1,16 +1,18 @@ using System.Collections.Generic; -namespace FreeSql.DatabaseModel { - public class DbTypeInfo { +namespace FreeSql.DatabaseModel +{ + public class DbTypeInfo + { - /// - /// 类型标识 - /// - public string Name { get; set; } + /// + /// 类型标识 + /// + public string Name { get; set; } - /// - /// 枚举项 - /// - public List<(string label, string value)> Labels { get; set; } - } + /// + /// 枚举项 + /// + public List<(string label, string value)> Labels { get; set; } + } } diff --git a/FreeSql/Extensions/EntityUtilExtensions.cs b/FreeSql/Extensions/EntityUtilExtensions.cs index f7bb3f2d..98ab49e7 100644 --- a/FreeSql/Extensions/EntityUtilExtensions.cs +++ b/FreeSql/Extensions/EntityUtilExtensions.cs @@ -6,655 +6,715 @@ using System.Linq.Expressions; using System.Reflection; using System.Text; -namespace FreeSql.Extensions.EntityUtil { - public static class EntityUtilExtensions { +namespace FreeSql.Extensions.EntityUtil +{ + public static class EntityUtilExtensions + { - static readonly MethodInfo MethodStringBuilderAppend = typeof(StringBuilder).GetMethod("Append", new Type[] { typeof(object) }); - static readonly MethodInfo MethodStringBuilderToString = typeof(StringBuilder).GetMethod("ToString", new Type[0]); - static readonly PropertyInfo MethodStringBuilderLength = typeof(StringBuilder).GetProperty("Length"); - static readonly MethodInfo MethodStringConcat = typeof(string).GetMethod("Concat", new Type[] { typeof(object) }); - static readonly MethodInfo MethodFreeUtilNewMongodbId = typeof(FreeUtil).GetMethod("NewMongodbId"); + static readonly MethodInfo MethodStringBuilderAppend = typeof(StringBuilder).GetMethod("Append", new Type[] { typeof(object) }); + static readonly MethodInfo MethodStringBuilderToString = typeof(StringBuilder).GetMethod("ToString", new Type[0]); + static readonly PropertyInfo MethodStringBuilderLength = typeof(StringBuilder).GetProperty("Length"); + static readonly MethodInfo MethodStringConcat = typeof(string).GetMethod("Concat", new Type[] { typeof(object) }); + static readonly MethodInfo MethodFreeUtilNewMongodbId = typeof(FreeUtil).GetMethod("NewMongodbId"); - static ConcurrentDictionary>> _dicGetEntityKeyString = new ConcurrentDictionary>>(); - /// - /// 获取实体的主键值,以 "*|_,[,_|*" 分割,当任意一个主键属性无值时,返回 null - /// - /// - /// - /// - /// 当Guid无值时,会生成有序的新值 - /// - /// - //public static string GetEntityKeyString(this IFreeSql orm, TEntity entity, string splitString = "*|_,[,_|*") => GetEntityKeyString(orm, typeof(TEntity), entity, splitString); - public static string GetEntityKeyString(this IFreeSql orm, Type entityType, object entity, bool genGuid, string splitString = "*|_,[,_|*") { - if (entity == null) return null; - if (entityType == null) entityType = entity.GetType(); - var func = _dicGetEntityKeyString.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var pks = _table.Primarys; - var returnTarget = Expression.Label(typeof(string)); - var parm1 = Expression.Parameter(typeof(object)); - var parm2 = Expression.Parameter(typeof(bool)); - var var1Parm = Expression.Variable(t); - var var2Sb = Expression.Variable(typeof(StringBuilder)); - var var3IsNull = Expression.Variable(typeof(bool)); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), - Expression.Assign(var2Sb, Expression.New(typeof(StringBuilder))), - Expression.Assign(var3IsNull, Expression.Constant(false)) - }); - for (var a = 0; a < pks.Length; a++) { - var isguid = pks[a].Attribute.MapType.NullableTypeOrThis() == typeof(Guid) || pks[a].CsType.NullableTypeOrThis() == typeof(Guid); - Expression expthen = null; - if (isguid) { - if (pks[a].Attribute.MapType == pks[a].CsType) { - expthen = Expression.Block( - new Expression[]{ - Expression.Assign(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), Expression.Call(MethodFreeUtilNewMongodbId)), - a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, - Expression.Call(var2Sb, MethodStringBuilderAppend, - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) - ) - }.Where(c => c != null).ToArray() - ); - } else { - expthen = Expression.Block( - new Expression[]{ - Expression.Assign(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(pks[a].CsType, Expression.Call(MethodFreeUtilNewMongodbId))), - a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, - Expression.Call(var2Sb, MethodStringBuilderAppend, - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) - ) - }.Where(c => c != null).ToArray() - ); - } - } else if (pks.Length > 1 && pks[a].Attribute.IsIdentity) { - expthen = Expression.Block( - new Expression[]{ - a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, - Expression.Call(var2Sb, MethodStringBuilderAppend, - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) - ) - }.Where(c => c != null).ToArray() - ); - } else { - expthen = Expression.Assign(var3IsNull, Expression.Constant(true)); - } - if (pks[a].Attribute.IsIdentity || isguid || pks[a].CsType == typeof(string) || pks[a].CsType.IsNullableType()) { - exps.Add( - Expression.IfThen( - Expression.IsFalse(var3IsNull), - Expression.IfThenElse( - Expression.Equal(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), Expression.Default(pks[a].CsType)), - Expression.IfThen( - Expression.IsTrue(parm2), - expthen - ), - Expression.Block( - new Expression[]{ - a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, - Expression.Call(var2Sb, MethodStringBuilderAppend, - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) - ) - }.Where(c => c != null).ToArray() - ) - ) - ) - ); - } else { - exps.Add( - Expression.IfThen( - Expression.IsFalse(var3IsNull), - Expression.Block( - new Expression[]{ - a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, - Expression.Call(var2Sb, MethodStringBuilderAppend, - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) - ) - }.Where(c => c != null).ToArray() - ) - ) - ); - } - } - exps.Add( - Expression.IfThen( - Expression.IsFalse(var3IsNull), - Expression.Return(returnTarget, Expression.Call(var2Sb, MethodStringBuilderToString)) - ) - ); - exps.Add(Expression.Label(returnTarget, Expression.Default(typeof(string)))); - return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Sb, var3IsNull }, exps), new[] { parm1, parm2 }).Compile(); - }); - return func(entity, genGuid); - } - static ConcurrentDictionary>> _dicGetEntityKeyValues = new ConcurrentDictionary>>(); - /// - /// 获取实体的主键值,多个主键返回数组 - /// - /// - /// - /// - /// - //public static object[] GetEntityKeyValues(this IFreeSql orm, TEntity entity) => GetEntityKeyValues(orm, typeof(TEntity), entity); - public static object[] GetEntityKeyValues(this IFreeSql orm, Type entityType, object entity) { - if (entity == null) return null; - if (entityType == null) entityType = entity.GetType(); - var func = _dicGetEntityKeyValues.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var pks = _table.Primarys; - var returnTarget = Expression.Label(typeof(object[])); - var parm1 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(t); - var var2Ret = Expression.Variable(typeof(object[])); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), - Expression.Assign(var2Ret, Expression.NewArrayBounds(typeof(object), Expression.Constant(pks.Length))), - }); - for (var a = 0; a < pks.Length; a++) { - exps.Add( - Expression.Assign( - Expression.ArrayAccess(var2Ret, Expression.Constant(a)), - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) - ) - ); - } - exps.AddRange(new Expression[] { - Expression.Return(returnTarget, var2Ret), - Expression.Label(returnTarget, Expression.Default(typeof(object[]))) - }); - return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Ret }, exps), new[] { parm1 }).Compile(); - }); - return func(entity); - } - static ConcurrentDictionary>>> _dicGetEntityValueWithPropertyName = new ConcurrentDictionary>>>(); - /// - /// 获取实体的属性值 - /// - /// - /// - /// - /// - /// - //public static object GetEntityValueWithPropertyName(this IFreeSql orm, TEntity entity, string propertyName) => GetEntityKeyValues(orm, typeof(TEntity), entity, propertyName); - public static object GetEntityValueWithPropertyName(this IFreeSql orm, Type entityType, object entity, string propertyName) { - if (entity == null) return null; - if (entityType == null) entityType = entity.GetType(); - var func = _dicGetEntityValueWithPropertyName - .GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>>()) - .GetOrAdd(entityType, et => new ConcurrentDictionary>()) - .GetOrAdd(propertyName, pn => { - var _table = orm.CodeFirst.GetTableByEntity(entityType); - var pks = _table.Primarys; - var returnTarget = Expression.Label(typeof(object)); - var parm1 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(entityType); - var var2Ret = Expression.Variable(typeof(object)); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, entityType)), - Expression.Assign( - var2Ret, - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pn]), typeof(object)) - ) - }); - exps.AddRange(new Expression[] { - Expression.Return(returnTarget, var2Ret), - Expression.Label(returnTarget, Expression.Default(typeof(object))) - }); - return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Ret }, exps), new[] { parm1 }).Compile(); - }); - return func(entity); - } - static ConcurrentDictionary>> _dicGetEntityString = new ConcurrentDictionary>>(); - /// - /// 获取实体的所有数据,以 (1, 2, xxx) 的形式 - /// - /// - /// - /// - /// - //public static string GetEntityString(this IFreeSql orm, TEntity entity) => GetEntityString(orm, typeof(TEntity), entity); - public static string GetEntityString(this IFreeSql orm, Type entityType, object entity) { - if (entity == null) return null; - if (entityType == null) entityType = entity.GetType(); - var func = _dicGetEntityString.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var cols = _table.Columns; - var returnTarget = Expression.Label(typeof(string)); - var parm1 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(t); - var var2Sb = Expression.Variable(typeof(StringBuilder)); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), - Expression.Assign(var2Sb, Expression.New(typeof(StringBuilder))), - Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant("(" )) - }); - var a = 0; - foreach (var col in cols.Values) { - exps.Add( - Expression.Block( - new Expression[]{ - a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(", " )) : null, - Expression.Call(var2Sb, MethodStringBuilderAppend, - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[col.CsName]), typeof(object)) - ) - }.Where(c => c != null).ToArray() - ) - ); - a++; - } - exps.AddRange(new Expression[] { - Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(")" )), - Expression.Return(returnTarget, Expression.Call(var2Sb, MethodStringBuilderToString)), - Expression.Label(returnTarget, Expression.Default(typeof(string))) - }); - return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Sb }, exps), new[] { parm1 }).Compile(); - }); - return func(entity); - } + static ConcurrentDictionary>> _dicGetEntityKeyString = new ConcurrentDictionary>>(); + /// + /// 获取实体的主键值,以 "*|_,[,_|*" 分割,当任意一个主键属性无值时,返回 null + /// + /// + /// + /// + /// 当Guid无值时,会生成有序的新值 + /// + /// + //public static string GetEntityKeyString(this IFreeSql orm, TEntity entity, string splitString = "*|_,[,_|*") => GetEntityKeyString(orm, typeof(TEntity), entity, splitString); + public static string GetEntityKeyString(this IFreeSql orm, Type entityType, object entity, bool genGuid, string splitString = "*|_,[,_|*") + { + if (entity == null) return null; + if (entityType == null) entityType = entity.GetType(); + var func = _dicGetEntityKeyString.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var pks = _table.Primarys; + var returnTarget = Expression.Label(typeof(string)); + var parm1 = Expression.Parameter(typeof(object)); + var parm2 = Expression.Parameter(typeof(bool)); + var var1Parm = Expression.Variable(t); + var var2Sb = Expression.Variable(typeof(StringBuilder)); + var var3IsNull = Expression.Variable(typeof(bool)); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), + Expression.Assign(var2Sb, Expression.New(typeof(StringBuilder))), + Expression.Assign(var3IsNull, Expression.Constant(false)) + }); + for (var a = 0; a < pks.Length; a++) + { + var isguid = pks[a].Attribute.MapType.NullableTypeOrThis() == typeof(Guid) || pks[a].CsType.NullableTypeOrThis() == typeof(Guid); + Expression expthen = null; + if (isguid) + { + if (pks[a].Attribute.MapType == pks[a].CsType) + { + expthen = Expression.Block( + new Expression[]{ + Expression.Assign(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), Expression.Call(MethodFreeUtilNewMongodbId)), + a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, + Expression.Call(var2Sb, MethodStringBuilderAppend, + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) + ) + }.Where(c => c != null).ToArray() + ); + } + else + { + expthen = Expression.Block( + new Expression[]{ + Expression.Assign(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(pks[a].CsType, Expression.Call(MethodFreeUtilNewMongodbId))), + a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, + Expression.Call(var2Sb, MethodStringBuilderAppend, + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) + ) + }.Where(c => c != null).ToArray() + ); + } + } + else if (pks.Length > 1 && pks[a].Attribute.IsIdentity) + { + expthen = Expression.Block( + new Expression[]{ + a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, + Expression.Call(var2Sb, MethodStringBuilderAppend, + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) + ) + }.Where(c => c != null).ToArray() + ); + } + else + { + expthen = Expression.Assign(var3IsNull, Expression.Constant(true)); + } + if (pks[a].Attribute.IsIdentity || isguid || pks[a].CsType == typeof(string) || pks[a].CsType.IsNullableType()) + { + exps.Add( + Expression.IfThen( + Expression.IsFalse(var3IsNull), + Expression.IfThenElse( + Expression.Equal(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), Expression.Default(pks[a].CsType)), + Expression.IfThen( + Expression.IsTrue(parm2), + expthen + ), + Expression.Block( + new Expression[]{ + a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, + Expression.Call(var2Sb, MethodStringBuilderAppend, + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) + ) + }.Where(c => c != null).ToArray() + ) + ) + ) + ); + } + else + { + exps.Add( + Expression.IfThen( + Expression.IsFalse(var3IsNull), + Expression.Block( + new Expression[]{ + a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(splitString)) : null, + Expression.Call(var2Sb, MethodStringBuilderAppend, + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) + ) + }.Where(c => c != null).ToArray() + ) + ) + ); + } + } + exps.Add( + Expression.IfThen( + Expression.IsFalse(var3IsNull), + Expression.Return(returnTarget, Expression.Call(var2Sb, MethodStringBuilderToString)) + ) + ); + exps.Add(Expression.Label(returnTarget, Expression.Default(typeof(string)))); + return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Sb, var3IsNull }, exps), new[] { parm1, parm2 }).Compile(); + }); + return func(entity, genGuid); + } + static ConcurrentDictionary>> _dicGetEntityKeyValues = new ConcurrentDictionary>>(); + /// + /// 获取实体的主键值,多个主键返回数组 + /// + /// + /// + /// + /// + //public static object[] GetEntityKeyValues(this IFreeSql orm, TEntity entity) => GetEntityKeyValues(orm, typeof(TEntity), entity); + public static object[] GetEntityKeyValues(this IFreeSql orm, Type entityType, object entity) + { + if (entity == null) return null; + if (entityType == null) entityType = entity.GetType(); + var func = _dicGetEntityKeyValues.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var pks = _table.Primarys; + var returnTarget = Expression.Label(typeof(object[])); + var parm1 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(t); + var var2Ret = Expression.Variable(typeof(object[])); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), + Expression.Assign(var2Ret, Expression.NewArrayBounds(typeof(object), Expression.Constant(pks.Length))), + }); + for (var a = 0; a < pks.Length; a++) + { + exps.Add( + Expression.Assign( + Expression.ArrayAccess(var2Ret, Expression.Constant(a)), + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pks[a].CsName]), typeof(object)) + ) + ); + } + exps.AddRange(new Expression[] { + Expression.Return(returnTarget, var2Ret), + Expression.Label(returnTarget, Expression.Default(typeof(object[]))) + }); + return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Ret }, exps), new[] { parm1 }).Compile(); + }); + return func(entity); + } + static ConcurrentDictionary>>> _dicGetEntityValueWithPropertyName = new ConcurrentDictionary>>>(); + /// + /// 获取实体的属性值 + /// + /// + /// + /// + /// + /// + //public static object GetEntityValueWithPropertyName(this IFreeSql orm, TEntity entity, string propertyName) => GetEntityKeyValues(orm, typeof(TEntity), entity, propertyName); + public static object GetEntityValueWithPropertyName(this IFreeSql orm, Type entityType, object entity, string propertyName) + { + if (entity == null) return null; + if (entityType == null) entityType = entity.GetType(); + var func = _dicGetEntityValueWithPropertyName + .GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>>()) + .GetOrAdd(entityType, et => new ConcurrentDictionary>()) + .GetOrAdd(propertyName, pn => + { + var _table = orm.CodeFirst.GetTableByEntity(entityType); + var pks = _table.Primarys; + var returnTarget = Expression.Label(typeof(object)); + var parm1 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(entityType); + var var2Ret = Expression.Variable(typeof(object)); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, entityType)), + Expression.Assign( + var2Ret, + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[pn]), typeof(object)) + ) + }); + exps.AddRange(new Expression[] { + Expression.Return(returnTarget, var2Ret), + Expression.Label(returnTarget, Expression.Default(typeof(object))) + }); + return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Ret }, exps), new[] { parm1 }).Compile(); + }); + return func(entity); + } + static ConcurrentDictionary>> _dicGetEntityString = new ConcurrentDictionary>>(); + /// + /// 获取实体的所有数据,以 (1, 2, xxx) 的形式 + /// + /// + /// + /// + /// + //public static string GetEntityString(this IFreeSql orm, TEntity entity) => GetEntityString(orm, typeof(TEntity), entity); + public static string GetEntityString(this IFreeSql orm, Type entityType, object entity) + { + if (entity == null) return null; + if (entityType == null) entityType = entity.GetType(); + var func = _dicGetEntityString.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var cols = _table.Columns; + var returnTarget = Expression.Label(typeof(string)); + var parm1 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(t); + var var2Sb = Expression.Variable(typeof(StringBuilder)); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), + Expression.Assign(var2Sb, Expression.New(typeof(StringBuilder))), + Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant("(" )) + }); + var a = 0; + foreach (var col in cols.Values) + { + exps.Add( + Expression.Block( + new Expression[]{ + a > 0 ? Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(", " )) : null, + Expression.Call(var2Sb, MethodStringBuilderAppend, + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[col.CsName]), typeof(object)) + ) + }.Where(c => c != null).ToArray() + ) + ); + a++; + } + exps.AddRange(new Expression[] { + Expression.Call(var2Sb, MethodStringBuilderAppend, Expression.Constant(")" )), + Expression.Return(returnTarget, Expression.Call(var2Sb, MethodStringBuilderToString)), + Expression.Label(returnTarget, Expression.Default(typeof(string))) + }); + return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Sb }, exps), new[] { parm1 }).Compile(); + }); + return func(entity); + } - /// - /// 使用新实体的值,复盖旧实体的值 - /// - static ConcurrentDictionary>> _dicMapEntityValue = new ConcurrentDictionary>>(); - //public static void MapEntityValue(this IFreeSql orm, TEntity entityFrom, TEntity entityTo) => MapEntityValue(orm, typeof(TEntity), entityFrom, entityTo); - public static void MapEntityValue(this IFreeSql orm, Type entityType, object entityFrom, object entityTo) { - if (entityType == null) entityType = entityFrom?.GetType() ?? entityTo?.GetType(); - var func = _dicMapEntityValue.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var parm1 = Expression.Parameter(typeof(object)); - var parm2 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(t); - var var2Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), - Expression.Assign(var2Parm, Expression.TypeAs(parm2, t)) - }); - foreach (var prop in _table.Properties.Values) { - if (_table.ColumnsByCsIgnore.ContainsKey(prop.Name)) continue; - if (_table.ColumnsByCs.ContainsKey(prop.Name)) { - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var2Parm, prop), - Expression.MakeMemberAccess(var1Parm, prop) - ) - ); - } - - //else if (prop.GetSetMethod() != null) { - // exps.Add( - // Expression.Assign( - // Expression.MakeMemberAccess(var2Parm, prop), - // Expression.Default(prop.PropertyType) - // ) - // ); - //} - } - return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Parm }, exps), new[] { parm1, parm2 }).Compile(); - }); - func(entityFrom, entityTo); - } + /// + /// 使用新实体的值,复盖旧实体的值 + /// + static ConcurrentDictionary>> _dicMapEntityValue = new ConcurrentDictionary>>(); + //public static void MapEntityValue(this IFreeSql orm, TEntity entityFrom, TEntity entityTo) => MapEntityValue(orm, typeof(TEntity), entityFrom, entityTo); + public static void MapEntityValue(this IFreeSql orm, Type entityType, object entityFrom, object entityTo) + { + if (entityType == null) entityType = entityFrom?.GetType() ?? entityTo?.GetType(); + var func = _dicMapEntityValue.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var parm1 = Expression.Parameter(typeof(object)); + var parm2 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(t); + var var2Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), + Expression.Assign(var2Parm, Expression.TypeAs(parm2, t)) + }); + foreach (var prop in _table.Properties.Values) + { + if (_table.ColumnsByCsIgnore.ContainsKey(prop.Name)) continue; + if (_table.ColumnsByCs.ContainsKey(prop.Name)) + { + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var2Parm, prop), + Expression.MakeMemberAccess(var1Parm, prop) + ) + ); + } - static ConcurrentDictionary>> _dicMapEntityKeyValue = new ConcurrentDictionary>>(); - /// - /// 使用新实体的主键值,复盖旧实体的主键值 - /// - //public static void MapEntityKeyValue(this IFreeSql orm, TEntity entityFrom, TEntity entityTo) => MapEntityKeyValue(orm, typeof(TEntity), entityFrom, entityTo); - public static void MapEntityKeyValue(this IFreeSql orm, Type entityType, object entityFrom, object entityTo) { - if (entityType == null) entityType = entityFrom?.GetType() ?? entityTo?.GetType(); - var func = _dicMapEntityKeyValue.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var pks = _table.Primarys; - var parm1 = Expression.Parameter(typeof(object)); - var parm2 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(t); - var var2Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), - Expression.Assign(var2Parm, Expression.TypeAs(parm2, t)) - }); - foreach (var pk in pks) { - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var2Parm, _table.Properties[pk.CsName]), - Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]) - ) - ); - } - return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Parm }, exps), new[] { parm1, parm2 }).Compile(); - }); - func(entityFrom, entityTo); - } + //else if (prop.GetSetMethod() != null) { + // exps.Add( + // Expression.Assign( + // Expression.MakeMemberAccess(var2Parm, prop), + // Expression.Default(prop.PropertyType) + // ) + // ); + //} + } + return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Parm }, exps), new[] { parm1, parm2 }).Compile(); + }); + func(entityFrom, entityTo); + } - static ConcurrentDictionary>> _dicSetEntityIdentityValueWithPrimary = new ConcurrentDictionary>>(); - /// - /// 设置实体中主键内的自增字段值(若存在) - /// - /// - /// - /// - /// - //public static void SetEntityIdentityValueWithPrimary(this IFreeSql orm, TEntity entity, long idtval) => SetEntityIdentityValueWithPrimary(orm, typeof(TEntity), entity, idtval); - public static void SetEntityIdentityValueWithPrimary(this IFreeSql orm, Type entityType, object entity, long idtval) { - if (entity == null) return; - if (entityType == null) entityType = entity.GetType(); - var func = _dicSetEntityIdentityValueWithPrimary.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity); - var parm1 = Expression.Parameter(typeof(object)); - var parm2 = Expression.Parameter(typeof(long)); - var var1Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) - }); - if (identitys.Any()) { - var idts0 = identitys.First(); - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]), - Expression.Convert(FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(idts0.CsType, Expression.Convert(parm2, typeof(object))), idts0.CsType) - ) - ); - } - return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2 }).Compile(); - }); - func(entity, idtval); - } - static ConcurrentDictionary>> _dicGetEntityIdentityValueWithPrimary = new ConcurrentDictionary>>(); - /// - /// 获取实体中主键内的自增字段值(若存在) - /// - /// - /// - /// - //public static long GetEntityIdentityValueWithPrimary(this IFreeSql orm, TEntity entity) => GetEntityIdentityValueWithPrimary(orm, typeof(TEntity), entity); - public static long GetEntityIdentityValueWithPrimary(this IFreeSql orm, Type entityType, object entity) { - if (entity == null) return 0; - if (entityType == null) entityType = entity.GetType(); - var func = _dicGetEntityIdentityValueWithPrimary.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity); - var returnTarget = Expression.Label(typeof(long)); - var parm1 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) - }); - if (identitys.Any()) { - var idts0 = identitys.First(); - exps.Add( - Expression.IfThen( - Expression.NotEqual( - Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]), - Expression.Default(idts0.CsType) - ), - Expression.Return( - returnTarget, - Expression.Convert( - FreeSql.Internal.Utils.GetDataReaderValueBlockExpression( - typeof(long), - Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]), typeof(object)) - ), - typeof(long) - ) - ) - ) - ); - } - exps.Add(Expression.Label(returnTarget, Expression.Default(typeof(long)))); - return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1 }).Compile(); - }); - return func(entity); - } + static ConcurrentDictionary>> _dicMapEntityKeyValue = new ConcurrentDictionary>>(); + /// + /// 使用新实体的主键值,复盖旧实体的主键值 + /// + //public static void MapEntityKeyValue(this IFreeSql orm, TEntity entityFrom, TEntity entityTo) => MapEntityKeyValue(orm, typeof(TEntity), entityFrom, entityTo); + public static void MapEntityKeyValue(this IFreeSql orm, Type entityType, object entityFrom, object entityTo) + { + if (entityType == null) entityType = entityFrom?.GetType() ?? entityTo?.GetType(); + var func = _dicMapEntityKeyValue.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var pks = _table.Primarys; + var parm1 = Expression.Parameter(typeof(object)); + var parm2 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(t); + var var2Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), + Expression.Assign(var2Parm, Expression.TypeAs(parm2, t)) + }); + foreach (var pk in pks) + { + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var2Parm, _table.Properties[pk.CsName]), + Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]) + ) + ); + } + return Expression.Lambda>(Expression.Block(new[] { var1Parm, var2Parm }, exps), new[] { parm1, parm2 }).Compile(); + }); + func(entityFrom, entityTo); + } - static ConcurrentDictionary>> _dicClearEntityPrimaryValueWithIdentityAndGuid = new ConcurrentDictionary>>(); - /// - /// 清除实体的主键值,将自增、Guid类型的主键值清除 - /// - /// - /// - /// - //public static void ClearEntityPrimaryValueWithIdentityAndGuid(this IFreeSql orm, TEntity entity) => ClearEntityPrimaryValueWithIdentityAndGuid(orm, typeof(TEntity), entity); - public static void ClearEntityPrimaryValueWithIdentityAndGuid(this IFreeSql orm, Type entityType, object entity) { - if (entity == null) return; - if (entityType == null) entityType = entity.GetType(); - var func = _dicClearEntityPrimaryValueWithIdentityAndGuid.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity); - var parm1 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) - }); - foreach (var pk in _table.Primarys) { - if (pk.Attribute.IsIdentity || pk.Attribute.MapType == pk.CsType && pk.Attribute.MapType.NullableTypeOrThis() == typeof(Guid)) { - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]), - Expression.Default(pk.CsType) - ) - ); - continue; - } - if (pk.Attribute.MapType != pk.CsType && (pk.Attribute.MapType.NullableTypeOrThis() == typeof(Guid) || pk.CsType.NullableTypeOrThis() == typeof(Guid))) { - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]), - FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(pk.CsType, Expression.Default(pk.Attribute.MapType)) - ) - ); - continue; - } - } - return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1 }).Compile(); - }); - func(entity); - } + static ConcurrentDictionary>> _dicSetEntityIdentityValueWithPrimary = new ConcurrentDictionary>>(); + /// + /// 设置实体中主键内的自增字段值(若存在) + /// + /// + /// + /// + /// + //public static void SetEntityIdentityValueWithPrimary(this IFreeSql orm, TEntity entity, long idtval) => SetEntityIdentityValueWithPrimary(orm, typeof(TEntity), entity, idtval); + public static void SetEntityIdentityValueWithPrimary(this IFreeSql orm, Type entityType, object entity, long idtval) + { + if (entity == null) return; + if (entityType == null) entityType = entity.GetType(); + var func = _dicSetEntityIdentityValueWithPrimary.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity); + var parm1 = Expression.Parameter(typeof(object)); + var parm2 = Expression.Parameter(typeof(long)); + var var1Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) + }); + if (identitys.Any()) + { + var idts0 = identitys.First(); + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]), + Expression.Convert(FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(idts0.CsType, Expression.Convert(parm2, typeof(object))), idts0.CsType) + ) + ); + } + return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2 }).Compile(); + }); + func(entity, idtval); + } + static ConcurrentDictionary>> _dicGetEntityIdentityValueWithPrimary = new ConcurrentDictionary>>(); + /// + /// 获取实体中主键内的自增字段值(若存在) + /// + /// + /// + /// + //public static long GetEntityIdentityValueWithPrimary(this IFreeSql orm, TEntity entity) => GetEntityIdentityValueWithPrimary(orm, typeof(TEntity), entity); + public static long GetEntityIdentityValueWithPrimary(this IFreeSql orm, Type entityType, object entity) + { + if (entity == null) return 0; + if (entityType == null) entityType = entity.GetType(); + var func = _dicGetEntityIdentityValueWithPrimary.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity); + var returnTarget = Expression.Label(typeof(long)); + var parm1 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) + }); + if (identitys.Any()) + { + var idts0 = identitys.First(); + exps.Add( + Expression.IfThen( + Expression.NotEqual( + Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]), + Expression.Default(idts0.CsType) + ), + Expression.Return( + returnTarget, + Expression.Convert( + FreeSql.Internal.Utils.GetDataReaderValueBlockExpression( + typeof(long), + Expression.Convert(Expression.MakeMemberAccess(var1Parm, _table.Properties[idts0.CsName]), typeof(object)) + ), + typeof(long) + ) + ) + ) + ); + } + exps.Add(Expression.Label(returnTarget, Expression.Default(typeof(long)))); + return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1 }).Compile(); + }); + return func(entity); + } - static ConcurrentDictionary>> _dicClearEntityPrimaryValueWithIdentity = new ConcurrentDictionary>>(); - /// - /// 清除实体的主键值,将自增、Guid类型的主键值清除 - /// - /// - /// - /// - //public static void ClearEntityPrimaryValueWithIdentity(this IFreeSql orm, TEntity entity) => ClearEntityPrimaryValueWithIdentity(orm, typeof(TEntity), entity); - public static void ClearEntityPrimaryValueWithIdentity(this IFreeSql orm, Type entityType, object entity) { - if (entity == null) return; - if (entityType == null) entityType = entity.GetType(); - var func = _dicClearEntityPrimaryValueWithIdentity.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity); - var parm1 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) - }); - foreach (var pk in _table.Primarys) { - if (pk.Attribute.IsIdentity) { - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]), - Expression.Default(pk.CsType) - ) - ); - } - } - return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1 }).Compile(); - }); - func(entity); - } + static ConcurrentDictionary>> _dicClearEntityPrimaryValueWithIdentityAndGuid = new ConcurrentDictionary>>(); + /// + /// 清除实体的主键值,将自增、Guid类型的主键值清除 + /// + /// + /// + /// + //public static void ClearEntityPrimaryValueWithIdentityAndGuid(this IFreeSql orm, TEntity entity) => ClearEntityPrimaryValueWithIdentityAndGuid(orm, typeof(TEntity), entity); + public static void ClearEntityPrimaryValueWithIdentityAndGuid(this IFreeSql orm, Type entityType, object entity) + { + if (entity == null) return; + if (entityType == null) entityType = entity.GetType(); + var func = _dicClearEntityPrimaryValueWithIdentityAndGuid.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity); + var parm1 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) + }); + foreach (var pk in _table.Primarys) + { + if (pk.Attribute.IsIdentity || pk.Attribute.MapType == pk.CsType && pk.Attribute.MapType.NullableTypeOrThis() == typeof(Guid)) + { + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]), + Expression.Default(pk.CsType) + ) + ); + continue; + } + if (pk.Attribute.MapType != pk.CsType && (pk.Attribute.MapType.NullableTypeOrThis() == typeof(Guid) || pk.CsType.NullableTypeOrThis() == typeof(Guid))) + { + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]), + FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(pk.CsType, Expression.Default(pk.Attribute.MapType)) + ) + ); + continue; + } + } + return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1 }).Compile(); + }); + func(entity); + } - static ConcurrentDictionary>> _dicCompareEntityValueReturnColumns = new ConcurrentDictionary>>(); - /// - /// 对比两个实体值,返回相同/或不相同的列名 - /// - /// - /// - /// - /// - /// - /// - //public static string[] CompareEntityValueReturnColumns(this IFreeSql orm, TEntity entity1, TEntity entity2, bool isEqual) => CompareEntityValueReturnColumns(orm, typeof(TEntity), entity1, entity2, isEqual); - public static string[] CompareEntityValueReturnColumns(this IFreeSql orm, Type entityType, object entity1, object entity2, bool isEqual) { - if (entityType == null) entityType = entity1?.GetType() ?? entity2?.GetType(); - var func = _dicCompareEntityValueReturnColumns.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var returnTarget = Expression.Label(typeof(string[])); - var parm1 = Expression.Parameter(typeof(object)); - var parm2 = Expression.Parameter(typeof(object)); - var parm3 = Expression.Parameter(typeof(bool)); - var var1Ret = Expression.Variable(typeof(List)); - var var1Parm = Expression.Variable(t); - var var2Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), - Expression.Assign(var2Parm, Expression.TypeAs(parm2, t)), - Expression.Assign(var1Ret, Expression.New(typeof(List))) - }); - var a = 0; - foreach (var prop in _table.Properties.Values) { - if (_table.ColumnsByCs.TryGetValue(prop.Name, out var trycol) == false) continue; - exps.Add( - Expression.IfThenElse( - Expression.Equal( - Expression.MakeMemberAccess(var1Parm, prop), - Expression.MakeMemberAccess(var2Parm, prop) - ), - Expression.IfThen( - Expression.IsTrue(parm3), - Expression.Call(var1Ret, typeof(List).GetMethod("Add", new Type[] { typeof(string) }), Expression.Constant(trycol.Attribute.Name)) - ), - Expression.IfThen( - Expression.IsFalse(parm3), - Expression.Call(var1Ret, typeof(List).GetMethod("Add", new Type[] { typeof(string) }), Expression.Constant(trycol.Attribute.Name)) - ) - ) - ); - a++; - } - exps.Add(Expression.Return(returnTarget, Expression.Call(var1Ret, typeof(List).GetMethod("ToArray", new Type[0])))); - exps.Add(Expression.Label(returnTarget, Expression.Constant(new string[0]))); - return Expression.Lambda>(Expression.Block(new[] { var1Ret, var1Parm, var2Parm }, exps), new[] { parm1, parm2, parm3 }).Compile(); - }); - return func(entity1, entity2, isEqual); - } + static ConcurrentDictionary>> _dicClearEntityPrimaryValueWithIdentity = new ConcurrentDictionary>>(); + /// + /// 清除实体的主键值,将自增、Guid类型的主键值清除 + /// + /// + /// + /// + //public static void ClearEntityPrimaryValueWithIdentity(this IFreeSql orm, TEntity entity) => ClearEntityPrimaryValueWithIdentity(orm, typeof(TEntity), entity); + public static void ClearEntityPrimaryValueWithIdentity(this IFreeSql orm, Type entityType, object entity) + { + if (entity == null) return; + if (entityType == null) entityType = entity.GetType(); + var func = _dicClearEntityPrimaryValueWithIdentity.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var identitys = _table.Primarys.Where(a => a.Attribute.IsIdentity); + var parm1 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) + }); + foreach (var pk in _table.Primarys) + { + if (pk.Attribute.IsIdentity) + { + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var1Parm, _table.Properties[pk.CsName]), + Expression.Default(pk.CsType) + ) + ); + } + } + return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1 }).Compile(); + }); + func(entity); + } - static ConcurrentDictionary>> _dicSetEntityIncrByWithPropertyName = new ConcurrentDictionary>>(); - /// - /// 设置实体中某属性的数值增加指定的值 - /// - /// - /// - /// - /// - /// - //public static void SetEntityIncrByWithPropertyName(this IFreeSql orm, TEntity entity, string propertyName, int incrBy) => SetEntityIncrByWithPropertyName(orm, typeof(TEntity), entity, propertyName, incrBy); - public static void SetEntityIncrByWithPropertyName(this IFreeSql orm, Type entityType, object entity, string propertyName, int incrBy) { - if (entity == null) return; - if (entityType == null) entityType = entity.GetType(); - var func = _dicSetEntityIncrByWithPropertyName.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => { - var _table = orm.CodeFirst.GetTableByEntity(t); - var parm1 = Expression.Parameter(typeof(object)); - var parm2 = Expression.Parameter(typeof(string)); - var parm3 = Expression.Parameter(typeof(int)); - var var1Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) - }); - if (_table.Properties.ContainsKey(propertyName)) { - var prop = _table.Properties[propertyName]; - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var1Parm, prop), - Expression.Add( - Expression.MakeMemberAccess(var1Parm, prop), - Expression.Convert( - FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Convert(parm3, typeof(object))), - prop.PropertyType - ) - ) - ) - ); - } - return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile(); - }); - func(entity, propertyName, incrBy); - } + static ConcurrentDictionary>> _dicCompareEntityValueReturnColumns = new ConcurrentDictionary>>(); + /// + /// 对比两个实体值,返回相同/或不相同的列名 + /// + /// + /// + /// + /// + /// + /// + //public static string[] CompareEntityValueReturnColumns(this IFreeSql orm, TEntity entity1, TEntity entity2, bool isEqual) => CompareEntityValueReturnColumns(orm, typeof(TEntity), entity1, entity2, isEqual); + public static string[] CompareEntityValueReturnColumns(this IFreeSql orm, Type entityType, object entity1, object entity2, bool isEqual) + { + if (entityType == null) entityType = entity1?.GetType() ?? entity2?.GetType(); + var func = _dicCompareEntityValueReturnColumns.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var returnTarget = Expression.Label(typeof(string[])); + var parm1 = Expression.Parameter(typeof(object)); + var parm2 = Expression.Parameter(typeof(object)); + var parm3 = Expression.Parameter(typeof(bool)); + var var1Ret = Expression.Variable(typeof(List)); + var var1Parm = Expression.Variable(t); + var var2Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)), + Expression.Assign(var2Parm, Expression.TypeAs(parm2, t)), + Expression.Assign(var1Ret, Expression.New(typeof(List))) + }); + var a = 0; + foreach (var prop in _table.Properties.Values) + { + if (_table.ColumnsByCs.TryGetValue(prop.Name, out var trycol) == false) continue; + exps.Add( + Expression.IfThenElse( + Expression.Equal( + Expression.MakeMemberAccess(var1Parm, prop), + Expression.MakeMemberAccess(var2Parm, prop) + ), + Expression.IfThen( + Expression.IsTrue(parm3), + Expression.Call(var1Ret, typeof(List).GetMethod("Add", new Type[] { typeof(string) }), Expression.Constant(trycol.Attribute.Name)) + ), + Expression.IfThen( + Expression.IsFalse(parm3), + Expression.Call(var1Ret, typeof(List).GetMethod("Add", new Type[] { typeof(string) }), Expression.Constant(trycol.Attribute.Name)) + ) + ) + ); + a++; + } + exps.Add(Expression.Return(returnTarget, Expression.Call(var1Ret, typeof(List).GetMethod("ToArray", new Type[0])))); + exps.Add(Expression.Label(returnTarget, Expression.Constant(new string[0]))); + return Expression.Lambda>(Expression.Block(new[] { var1Ret, var1Parm, var2Parm }, exps), new[] { parm1, parm2, parm3 }).Compile(); + }); + return func(entity1, entity2, isEqual); + } - static ConcurrentDictionary>>> _dicSetEntityValueWithPropertyName = new ConcurrentDictionary>>>(); - /// - /// 设置实体中某属性的值 - /// - /// - /// - /// - /// - /// - //public static void SetEntityValueWithPropertyName(this IFreeSql orm, TEntity entity, string propertyName, object value) => SetEntityValueWithPropertyName(orm, typeof(TEntity), entity, propertyName, value); - public static void SetEntityValueWithPropertyName(this IFreeSql orm, Type entityType, object entity, string propertyName, object value) { - if (entity == null) return; - if (entityType == null) entityType = entity.GetType(); - var func = _dicSetEntityValueWithPropertyName.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>>()) - .GetOrAdd(entityType, et => new ConcurrentDictionary>()) - .GetOrAdd(propertyName, pn => { - var t = entityType; - var _table = orm.CodeFirst.GetTableByEntity(t); - var parm1 = Expression.Parameter(typeof(object)); - var parm2 = Expression.Parameter(typeof(string)); - var parm3 = Expression.Parameter(typeof(object)); - var var1Parm = Expression.Variable(t); - var exps = new List(new Expression[] { - Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) - }); - if (_table.Properties.ContainsKey(pn)) { - var prop = _table.Properties[pn]; + static ConcurrentDictionary>> _dicSetEntityIncrByWithPropertyName = new ConcurrentDictionary>>(); + /// + /// 设置实体中某属性的数值增加指定的值 + /// + /// + /// + /// + /// + /// + //public static void SetEntityIncrByWithPropertyName(this IFreeSql orm, TEntity entity, string propertyName, int incrBy) => SetEntityIncrByWithPropertyName(orm, typeof(TEntity), entity, propertyName, incrBy); + public static void SetEntityIncrByWithPropertyName(this IFreeSql orm, Type entityType, object entity, string propertyName, int incrBy) + { + if (entity == null) return; + if (entityType == null) entityType = entity.GetType(); + var func = _dicSetEntityIncrByWithPropertyName.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>()).GetOrAdd(entityType, t => + { + var _table = orm.CodeFirst.GetTableByEntity(t); + var parm1 = Expression.Parameter(typeof(object)); + var parm2 = Expression.Parameter(typeof(string)); + var parm3 = Expression.Parameter(typeof(int)); + var var1Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) + }); + if (_table.Properties.ContainsKey(propertyName)) + { + var prop = _table.Properties[propertyName]; + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var1Parm, prop), + Expression.Add( + Expression.MakeMemberAccess(var1Parm, prop), + Expression.Convert( + FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Convert(parm3, typeof(object))), + prop.PropertyType + ) + ) + ) + ); + } + return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile(); + }); + func(entity, propertyName, incrBy); + } - if (_table.ColumnsByCs.ContainsKey(pn)) { - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var1Parm, prop), - Expression.Convert( - FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(prop.PropertyType, parm3), - prop.PropertyType - ) - ) - ); - } else { - exps.Add( - Expression.Assign( - Expression.MakeMemberAccess(var1Parm, prop), - Expression.Convert( - parm3, - prop.PropertyType - ) - ) - ); - } - } - return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile(); - }); - func(entity, propertyName, value); - } + static ConcurrentDictionary>>> _dicSetEntityValueWithPropertyName = new ConcurrentDictionary>>>(); + /// + /// 设置实体中某属性的值 + /// + /// + /// + /// + /// + /// + //public static void SetEntityValueWithPropertyName(this IFreeSql orm, TEntity entity, string propertyName, object value) => SetEntityValueWithPropertyName(orm, typeof(TEntity), entity, propertyName, value); + public static void SetEntityValueWithPropertyName(this IFreeSql orm, Type entityType, object entity, string propertyName, object value) + { + if (entity == null) return; + if (entityType == null) entityType = entity.GetType(); + var func = _dicSetEntityValueWithPropertyName.GetOrAdd(orm.Ado.DataType, dt => new ConcurrentDictionary>>()) + .GetOrAdd(entityType, et => new ConcurrentDictionary>()) + .GetOrAdd(propertyName, pn => + { + var t = entityType; + var _table = orm.CodeFirst.GetTableByEntity(t); + var parm1 = Expression.Parameter(typeof(object)); + var parm2 = Expression.Parameter(typeof(string)); + var parm3 = Expression.Parameter(typeof(object)); + var var1Parm = Expression.Variable(t); + var exps = new List(new Expression[] { + Expression.Assign(var1Parm, Expression.TypeAs(parm1, t)) + }); + if (_table.Properties.ContainsKey(pn)) + { + var prop = _table.Properties[pn]; - static ConcurrentDictionary _dicAppendEntityUpdateSetWithColumnMethods = new ConcurrentDictionary(); - static ConcurrentDictionary> _dicAppendEntityUpdateSetWithColumnMethod = new ConcurrentDictionary>(); - /// - /// 缓存执行 IUpdate.Set - /// - /// - /// - /// - /// - public static void AppendEntityUpdateSetWithColumn(this IUpdate update, Type columnType, LambdaExpression setExp) where TEntity : class { + if (_table.ColumnsByCs.ContainsKey(pn)) + { + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var1Parm, prop), + Expression.Convert( + FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(prop.PropertyType, parm3), + prop.PropertyType + ) + ) + ); + } + else + { + exps.Add( + Expression.Assign( + Expression.MakeMemberAccess(var1Parm, prop), + Expression.Convert( + parm3, + prop.PropertyType + ) + ) + ); + } + } + return Expression.Lambda>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile(); + }); + func(entity, propertyName, value); + } - var setMethod = _dicAppendEntityUpdateSetWithColumnMethod.GetOrAdd(typeof(IUpdate), uptp => new ConcurrentDictionary()).GetOrAdd(columnType, coltp => { - var allMethods = _dicAppendEntityUpdateSetWithColumnMethods.GetOrAdd(typeof(IUpdate), uptp => uptp.GetMethods()); - return allMethods.Where(a => a.Name == "Set" && a.IsGenericMethod && a.GetParameters().Length == 1 && a.GetGenericArguments().First().Name == "TMember").FirstOrDefault() - .MakeGenericMethod(columnType); - }); + static ConcurrentDictionary _dicAppendEntityUpdateSetWithColumnMethods = new ConcurrentDictionary(); + static ConcurrentDictionary> _dicAppendEntityUpdateSetWithColumnMethod = new ConcurrentDictionary>(); + /// + /// 缓存执行 IUpdate.Set + /// + /// + /// + /// + /// + public static void AppendEntityUpdateSetWithColumn(this IUpdate update, Type columnType, LambdaExpression setExp) where TEntity : class + { - setMethod.Invoke(update, new object[] { setExp }); - } - } + var setMethod = _dicAppendEntityUpdateSetWithColumnMethod.GetOrAdd(typeof(IUpdate), uptp => new ConcurrentDictionary()).GetOrAdd(columnType, coltp => + { + var allMethods = _dicAppendEntityUpdateSetWithColumnMethods.GetOrAdd(typeof(IUpdate), uptp => uptp.GetMethods()); + return allMethods.Where(a => a.Name == "Set" && a.IsGenericMethod && a.GetParameters().Length == 1 && a.GetGenericArguments().First().Name == "TMember").FirstOrDefault() + .MakeGenericMethod(columnType); + }); + + setMethod.Invoke(update, new object[] { setExp }); + } + } } diff --git a/FreeSql/Extensions/FreeSqlGlobalExtensions.cs b/FreeSql/Extensions/FreeSqlGlobalExtensions.cs index c5fde52a..68855572 100644 --- a/FreeSql/Extensions/FreeSqlGlobalExtensions.cs +++ b/FreeSql/Extensions/FreeSqlGlobalExtensions.cs @@ -8,84 +8,105 @@ using System.Drawing; using System.Linq; using System.Reflection; -public static partial class FreeSqlGlobalExtensions { +public static partial class FreeSqlGlobalExtensions +{ - public static FreeSql.ISelect Queryable(this IFreeSql freesql) where T : class => freesql.Select(); + public static FreeSql.ISelect Queryable(this IFreeSql freesql) where T : class => freesql.Select(); - static Lazy> dicIsNumberType = new Lazy>(() => new Dictionary { - [typeof(sbyte)] = true, [typeof(sbyte?)] = true, - [typeof(short)] = true, [typeof(short?)] = true, - [typeof(int)] = true, [typeof(int?)] = true, - [typeof(long)] = true, [typeof(long?)] = true, - [typeof(byte)] = true, [typeof(byte?)] = true, - [typeof(ushort)] = true, [typeof(ushort?)] = true, - [typeof(uint)] = true, [typeof(uint?)] = true, - [typeof(ulong)] = true, [typeof(ulong?)] = true, - [typeof(double)] = true, [typeof(double?)] = true, - [typeof(float)] = true, [typeof(float?)] = true, - [typeof(decimal)] = true, [typeof(decimal?)] = true - }); - public static bool IsNumberType(this Type that) => that == null ? false : dicIsNumberType.Value.ContainsKey(that); - public static bool IsNullableType(this Type that) => that?.FullName.StartsWith("System.Nullable`1[") == true; - public static bool IsAnonymousType(this Type that) => that?.FullName.StartsWith("<>f__AnonymousType") == true; - public static Type NullableTypeOrThis(this Type that) => that?.IsNullableType() == true ? that.GenericTypeArguments.First() : that; + static Lazy> dicIsNumberType = new Lazy>(() => new Dictionary + { + [typeof(sbyte)] = true, + [typeof(sbyte?)] = true, + [typeof(short)] = true, + [typeof(short?)] = true, + [typeof(int)] = true, + [typeof(int?)] = true, + [typeof(long)] = true, + [typeof(long?)] = true, + [typeof(byte)] = true, + [typeof(byte?)] = true, + [typeof(ushort)] = true, + [typeof(ushort?)] = true, + [typeof(uint)] = true, + [typeof(uint?)] = true, + [typeof(ulong)] = true, + [typeof(ulong?)] = true, + [typeof(double)] = true, + [typeof(double?)] = true, + [typeof(float)] = true, + [typeof(float?)] = true, + [typeof(decimal)] = true, + [typeof(decimal?)] = true + }); + public static bool IsNumberType(this Type that) => that == null ? false : dicIsNumberType.Value.ContainsKey(that); + public static bool IsNullableType(this Type that) => that?.FullName.StartsWith("System.Nullable`1[") == true; + public static bool IsAnonymousType(this Type that) => that?.FullName.StartsWith("<>f__AnonymousType") == true; + public static Type NullableTypeOrThis(this Type that) => that?.IsNullableType() == true ? that.GenericTypeArguments.First() : that; - /// - /// 测量两个经纬度的距离,返回单位:米 - /// - /// 经纬坐标1 - /// 经纬坐标2 - /// 返回距离(单位:米) - public static double Distance(this Point that, Point point) { - double radLat1 = (double)(that.Y) * Math.PI / 180d; - double radLng1 = (double)(that.X) * Math.PI / 180d; - double radLat2 = (double)(point.Y) * Math.PI / 180d; - double radLng2 = (double)(point.X) * Math.PI / 180d; - return 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((radLat1 - radLat2) / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin((radLng1 - radLng2) / 2), 2))) * 6378137; - } + /// + /// 测量两个经纬度的距离,返回单位:米 + /// + /// 经纬坐标1 + /// 经纬坐标2 + /// 返回距离(单位:米) + public static double Distance(this Point that, Point point) + { + double radLat1 = (double)(that.Y) * Math.PI / 180d; + double radLng1 = (double)(that.X) * Math.PI / 180d; + double radLat2 = (double)(point.Y) * Math.PI / 180d; + double radLng2 = (double)(point.X) * Math.PI / 180d; + return 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((radLat1 - radLat2) / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin((radLng1 - radLng2) / 2), 2))) * 6378137; + } - static ConcurrentDictionary _dicGetFields = new ConcurrentDictionary(); - public static object GetEnum(this IDataReader dr, int index) { - var value = dr.GetString(index); - var t = typeof(T); - var fs = _dicGetFields.GetOrAdd(t, t2 => t2.GetFields()); - foreach (var f in fs) - if (f.GetCustomAttribute()?.Description == value || f.Name == value) return Enum.Parse(t, f.Name, true); - return null; - } + static ConcurrentDictionary _dicGetFields = new ConcurrentDictionary(); + public static object GetEnum(this IDataReader dr, int index) + { + var value = dr.GetString(index); + var t = typeof(T); + var fs = _dicGetFields.GetOrAdd(t, t2 => t2.GetFields()); + foreach (var f in fs) + if (f.GetCustomAttribute()?.Description == value || f.Name == value) return Enum.Parse(t, f.Name, true); + return null; + } - public static string ToDescriptionOrString(this Enum item) { - string name = item.ToString(); - var desc = item.GetType().GetField(name)?.GetCustomAttribute(); - return desc?.Description ?? name; - } - public static long ToInt64(this Enum item) { - return Convert.ToInt64(item); - } - public static IEnumerable ToSet(this long value) { - var ret = new List(); - if (value == 0) return ret; - var t = typeof(T); - var fs = _dicGetFields.GetOrAdd(t, t2 => t2.GetFields()); - foreach (var f in fs) { - if (f.FieldType != t) continue; - object o = Enum.Parse(t, f.Name, true); - long v = (long)o; - if ((value & v) == v) ret.Add((T)o); - } - return ret; - } + public static string ToDescriptionOrString(this Enum item) + { + string name = item.ToString(); + var desc = item.GetType().GetField(name)?.GetCustomAttribute(); + return desc?.Description ?? name; + } + public static long ToInt64(this Enum item) + { + return Convert.ToInt64(item); + } + public static IEnumerable ToSet(this long value) + { + var ret = new List(); + if (value == 0) return ret; + var t = typeof(T); + var fs = _dicGetFields.GetOrAdd(t, t2 => t2.GetFields()); + foreach (var f in fs) + { + if (f.FieldType != t) continue; + object o = Enum.Parse(t, f.Name, true); + long v = (long)o; + if ((value & v) == v) ret.Add((T)o); + } + return ret; + } - /// - /// 将 IEnumable<T> 转成 ISelect<T>,以便使用 FreeSql 的查询功能。此方法用于 Lambad 表达式中,快速进行集合导航的查询。 - /// - /// - /// - /// - public static ISelect AsSelect(this IEnumerable that) where TEntity : class { - throw new NotImplementedException(); - } - public static ISelect AsSelect(this IEnumerable that, IFreeSql orm = null) where TEntity : class { - return orm?.Select(); - } + /// + /// 将 IEnumable<T> 转成 ISelect<T>,以便使用 FreeSql 的查询功能。此方法用于 Lambad 表达式中,快速进行集合导航的查询。 + /// + /// + /// + /// + public static ISelect AsSelect(this IEnumerable that) where TEntity : class + { + throw new NotImplementedException(); + } + public static ISelect AsSelect(this IEnumerable that, IFreeSql orm = null) where TEntity : class + { + return orm?.Select(); + } } \ No newline at end of file diff --git a/FreeSql/Extensions/LambadaExpressionExtensions.cs b/FreeSql/Extensions/LambadaExpressionExtensions.cs index 8a00b022..ff8e9b89 100644 --- a/FreeSql/Extensions/LambadaExpressionExtensions.cs +++ b/FreeSql/Extensions/LambadaExpressionExtensions.cs @@ -9,90 +9,99 @@ using System.Linq; using System.Linq.Expressions; using System.Reflection; -namespace System.Linq.Expressions { - public static partial class LambadaExpressionExtensions { +namespace System.Linq.Expressions +{ + public static partial class LambadaExpressionExtensions + { - /// - /// 使用 and 拼接两个 lambda 表达式 - /// - /// - public static Expression> And(this Expression> exp1, Expression> exp2) => And(exp1, true, exp2); - /// - /// 使用 and 拼接两个 lambda 表达式 - /// - /// - /// - /// true 时生效 - /// - /// - public static Expression> And(this Expression> exp1, bool condition, Expression> exp2) { - if (condition == false) return exp1; - if (exp1 == null) return exp2; - if (exp2 == null) return exp1; + /// + /// 使用 and 拼接两个 lambda 表达式 + /// + /// + public static Expression> And(this Expression> exp1, Expression> exp2) => And(exp1, true, exp2); + /// + /// 使用 and 拼接两个 lambda 表达式 + /// + /// + /// + /// true 时生效 + /// + /// + public static Expression> And(this Expression> exp1, bool condition, Expression> exp2) + { + if (condition == false) return exp1; + if (exp1 == null) return exp2; + if (exp2 == null) return exp1; - ParameterExpression newParameter = Expression.Parameter(typeof(T), "c"); - NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); + ParameterExpression newParameter = Expression.Parameter(typeof(T), "c"); + NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); - var left = visitor.Replace(exp1.Body); - var right = visitor.Replace(exp2.Body); - var body = Expression.AndAlso(left, right); - return Expression.Lambda>(body, newParameter); - } + var left = visitor.Replace(exp1.Body); + var right = visitor.Replace(exp2.Body); + var body = Expression.AndAlso(left, right); + return Expression.Lambda>(body, newParameter); + } - /// - /// 使用 or 拼接两个 lambda 表达式 - /// - /// - public static Expression> Or(this Expression> exp1, Expression> exp2) => Or(exp1, true, exp2); - /// - /// 使用 or 拼接两个 lambda 表达式 - /// - /// - /// - /// true 时生效 - /// - /// - public static Expression> Or(this Expression> exp1, bool condition, Expression> exp2) { - if (condition == false) return exp1; - if (exp1 == null) return exp2; - if (exp2 == null) return exp1; + /// + /// 使用 or 拼接两个 lambda 表达式 + /// + /// + public static Expression> Or(this Expression> exp1, Expression> exp2) => Or(exp1, true, exp2); + /// + /// 使用 or 拼接两个 lambda 表达式 + /// + /// + /// + /// true 时生效 + /// + /// + public static Expression> Or(this Expression> exp1, bool condition, Expression> exp2) + { + if (condition == false) return exp1; + if (exp1 == null) return exp2; + if (exp2 == null) return exp1; - ParameterExpression newParameter = Expression.Parameter(typeof(T), "c"); - NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); + ParameterExpression newParameter = Expression.Parameter(typeof(T), "c"); + NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter); - var left = visitor.Replace(exp1.Body); - var right = visitor.Replace(exp2.Body); - var body = Expression.OrElse(left, right); - return Expression.Lambda>(body, newParameter); - } + var left = visitor.Replace(exp1.Body); + var right = visitor.Replace(exp2.Body); + var body = Expression.OrElse(left, right); + return Expression.Lambda>(body, newParameter); + } - /// - /// 将 lambda 表达式取反 - /// - /// - /// - /// true 时生效 - /// - public static Expression> Not(this Expression> exp, bool condition = true) { - if (condition == false) return exp; - if (exp == null) return null; + /// + /// 将 lambda 表达式取反 + /// + /// + /// + /// true 时生效 + /// + public static Expression> Not(this Expression> exp, bool condition = true) + { + if (condition == false) return exp; + if (exp == null) return null; - var candidateExpr = exp.Parameters[0]; - var body = Expression.Not(exp.Body); - return Expression.Lambda>(body, candidateExpr); - } - } + var candidateExpr = exp.Parameters[0]; + var body = Expression.Not(exp.Body); + return Expression.Lambda>(body, candidateExpr); + } + } - internal class NewExpressionVisitor : ExpressionVisitor { - public ParameterExpression _newParameter { get; private set; } - public NewExpressionVisitor(ParameterExpression param) { - this._newParameter = param; - } - public Expression Replace(Expression exp) { - return this.Visit(exp); - } - protected override Expression VisitParameter(ParameterExpression node) { - return this._newParameter; - } - } + internal class NewExpressionVisitor : ExpressionVisitor + { + public ParameterExpression _newParameter { get; private set; } + public NewExpressionVisitor(ParameterExpression param) + { + this._newParameter = param; + } + public Expression Replace(Expression exp) + { + return this.Visit(exp); + } + protected override Expression VisitParameter(ParameterExpression node) + { + return this._newParameter; + } + } } \ No newline at end of file diff --git a/FreeSql/FreeSqlBuilder.cs b/FreeSql/FreeSqlBuilder.cs index 56fca2a8..3235583c 100644 --- a/FreeSql/FreeSqlBuilder.cs +++ b/FreeSql/FreeSqlBuilder.cs @@ -5,106 +5,117 @@ using System.Reflection; using FreeSql.DataAnnotations; using FreeSql.Internal; -namespace FreeSql { - public class FreeSqlBuilder { - DataType _dataType; - string _masterConnectionString; - string[] _slaveConnectionString; - bool _isAutoSyncStructure = false; - bool _isSyncStructureToLower = false; - bool _isSyncStructureToUpper = false; - bool _isConfigEntityFromDbFirst = false; - bool _isNoneCommandParameter = false; - bool _isLazyLoading = false; +namespace FreeSql +{ + public class FreeSqlBuilder + { + DataType _dataType; + string _masterConnectionString; + string[] _slaveConnectionString; + bool _isAutoSyncStructure = false; + bool _isSyncStructureToLower = false; + bool _isSyncStructureToUpper = false; + bool _isConfigEntityFromDbFirst = false; + bool _isNoneCommandParameter = false; + bool _isLazyLoading = false; StringConvertType _entityPropertyConvertType = StringConvertType.None; - Action _aopCommandExecuting = null; - Action _aopCommandExecuted = null; + Action _aopCommandExecuting = null; + Action _aopCommandExecuted = null; - /// - /// 使用连接串 - /// - /// 数据库类型 - /// 数据库连接串 - /// - public FreeSqlBuilder UseConnectionString(DataType dataType, string connectionString) { - _dataType = dataType; - _masterConnectionString = connectionString; - return this; - } - /// - /// 使用从数据库,支持多个 - /// - /// 从数据库连接串 - /// - public FreeSqlBuilder UseSlave(params string[] slaveConnectionString) { - _slaveConnectionString = slaveConnectionString; - return this; - } - /// - /// 【开发环境必备】自动同步实体结构到数据库,程序运行中检查实体表是否存在,然后创建或修改 - /// - /// true:运行时检查自动同步结构, false:不同步结构 - /// - public FreeSqlBuilder UseAutoSyncStructure(bool value) { - _isAutoSyncStructure = value; - return this; - } - /// - /// 转小写同步结构 - /// - /// true:转小写, false:不转 - /// - public FreeSqlBuilder UseSyncStructureToLower(bool value) { - _isSyncStructureToLower = value; - return this; - } - /// - /// 转大写同步结构 - /// - /// true:转大写, false:不转 - /// - public FreeSqlBuilder UseSyncStructureToUpper(bool value) { - _isSyncStructureToUpper = value; - return this; - } - /// - /// 使用数据库的主键和自增,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql。 - /// - /// - /// - public FreeSqlBuilder UseConfigEntityFromDbFirst(bool value) { - _isConfigEntityFromDbFirst = value; - return this; - } - /// - /// 不使用命令参数化执行,针对 Insert/Update,也可临时使用 IInsert/IUpdate.NoneParameter() - /// - /// - /// - public FreeSqlBuilder UseNoneCommandParameter(bool value) { - _isNoneCommandParameter = value; - return this; - } - /// - /// 延时加载导航属性对象,导航属性需要声明 virtual - /// - /// - /// - public FreeSqlBuilder UseLazyLoading(bool value) { - _isLazyLoading = value; - return this; - } - /// - /// 监视数据库命令对象 - /// - /// 执行前 - /// 执行后,可监视执行性能 - /// - public FreeSqlBuilder UseMonitorCommand(Action executing, Action executed = null) { - _aopCommandExecuting = executing; - _aopCommandExecuted = executed; - return this; - } + /// + /// 使用连接串 + /// + /// 数据库类型 + /// 数据库连接串 + /// + public FreeSqlBuilder UseConnectionString(DataType dataType, string connectionString) + { + _dataType = dataType; + _masterConnectionString = connectionString; + return this; + } + /// + /// 使用从数据库,支持多个 + /// + /// 从数据库连接串 + /// + public FreeSqlBuilder UseSlave(params string[] slaveConnectionString) + { + _slaveConnectionString = slaveConnectionString; + return this; + } + /// + /// 【开发环境必备】自动同步实体结构到数据库,程序运行中检查实体表是否存在,然后创建或修改 + /// + /// true:运行时检查自动同步结构, false:不同步结构 + /// + public FreeSqlBuilder UseAutoSyncStructure(bool value) + { + _isAutoSyncStructure = value; + return this; + } + /// + /// 转小写同步结构 + /// + /// true:转小写, false:不转 + /// + public FreeSqlBuilder UseSyncStructureToLower(bool value) + { + _isSyncStructureToLower = value; + return this; + } + /// + /// 转大写同步结构 + /// + /// true:转大写, false:不转 + /// + public FreeSqlBuilder UseSyncStructureToUpper(bool value) + { + _isSyncStructureToUpper = value; + return this; + } + /// + /// 使用数据库的主键和自增,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql。 + /// + /// + /// + public FreeSqlBuilder UseConfigEntityFromDbFirst(bool value) + { + _isConfigEntityFromDbFirst = value; + return this; + } + /// + /// 不使用命令参数化执行,针对 Insert/Update,也可临时使用 IInsert/IUpdate.NoneParameter() + /// + /// + /// + public FreeSqlBuilder UseNoneCommandParameter(bool value) + { + _isNoneCommandParameter = value; + return this; + } + /// + /// 延时加载导航属性对象,导航属性需要声明 virtual + /// + /// + /// + public FreeSqlBuilder UseLazyLoading(bool value) + { + _isLazyLoading = value; + return this; + } + /// + /// 监视数据库命令对象 + /// + /// 执行前 + /// 执行后,可监视执行性能 + /// + public FreeSqlBuilder UseMonitorCommand(Action executing, Action executed = null) + { + _aopCommandExecuting = executing; + _aopCommandExecuted = executed; + return this; + } /// /// 自动转换实体属性名称 Entity Property -> Db Filed @@ -120,78 +131,92 @@ namespace FreeSql { } public IFreeSql Build() => Build(); - public IFreeSql Build() { - if (string.IsNullOrEmpty(_masterConnectionString)) throw new Exception("参数 masterConnectionString 不可为空,请检查 UseConnectionString"); - IFreeSql ret = null; - Type type = null; - switch(_dataType) { - case DataType.MySql: - type = Type.GetType("FreeSql.MySql.MySqlProvider`1,FreeSql.Provider.MySql")?.MakeGenericType(typeof(TMark)); - if (type == null) type = Type.GetType("FreeSql.MySql.MySqlProvider`1,FreeSql.Provider.MySqlConnector")?.MakeGenericType(typeof(TMark)); - if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.MySql.dll,可前往 nuget 下载"); - break; - case DataType.SqlServer: type = Type.GetType("FreeSql.SqlServer.SqlServerProvider`1,FreeSql.Provider.SqlServer")?.MakeGenericType(typeof(TMark)); - if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.SqlServer.dll,可前往 nuget 下载"); - break; - case DataType.PostgreSQL: type = Type.GetType("FreeSql.PostgreSQL.PostgreSQLProvider`1,FreeSql.Provider.PostgreSQL")?.MakeGenericType(typeof(TMark)); - if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.PostgreSQL.dll,可前往 nuget 下载"); - break; - case DataType.Oracle: type = Type.GetType("FreeSql.Oracle.OracleProvider`1,FreeSql.Provider.Oracle")?.MakeGenericType(typeof(TMark)); - if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.Oracle.dll,可前往 nuget 下载"); - break; - case DataType.Sqlite: type = Type.GetType("FreeSql.Sqlite.SqliteProvider`1,FreeSql.Provider.Sqlite")?.MakeGenericType(typeof(TMark)); - if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.Sqlite.dll,可前往 nuget 下载"); - break; - default: throw new Exception("未指定 UseConnectionString"); - } - ret = Activator.CreateInstance(type, new object[] { _masterConnectionString, _slaveConnectionString }) as IFreeSql; - if (ret != null) { - ret.CodeFirst.IsAutoSyncStructure = _isAutoSyncStructure; + public IFreeSql Build() + { + if (string.IsNullOrEmpty(_masterConnectionString)) throw new Exception("参数 masterConnectionString 不可为空,请检查 UseConnectionString"); + IFreeSql ret = null; + Type type = null; + switch (_dataType) + { + case DataType.MySql: + type = Type.GetType("FreeSql.MySql.MySqlProvider`1,FreeSql.Provider.MySql")?.MakeGenericType(typeof(TMark)); + if (type == null) type = Type.GetType("FreeSql.MySql.MySqlProvider`1,FreeSql.Provider.MySqlConnector")?.MakeGenericType(typeof(TMark)); + if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.MySql.dll,可前往 nuget 下载"); + break; + case DataType.SqlServer: + type = Type.GetType("FreeSql.SqlServer.SqlServerProvider`1,FreeSql.Provider.SqlServer")?.MakeGenericType(typeof(TMark)); + if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.SqlServer.dll,可前往 nuget 下载"); + break; + case DataType.PostgreSQL: + type = Type.GetType("FreeSql.PostgreSQL.PostgreSQLProvider`1,FreeSql.Provider.PostgreSQL")?.MakeGenericType(typeof(TMark)); + if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.PostgreSQL.dll,可前往 nuget 下载"); + break; + case DataType.Oracle: + type = Type.GetType("FreeSql.Oracle.OracleProvider`1,FreeSql.Provider.Oracle")?.MakeGenericType(typeof(TMark)); + if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.Oracle.dll,可前往 nuget 下载"); + break; + case DataType.Sqlite: + type = Type.GetType("FreeSql.Sqlite.SqliteProvider`1,FreeSql.Provider.Sqlite")?.MakeGenericType(typeof(TMark)); + if (type == null) throw new Exception("缺少 FreeSql 数据库实现包:FreeSql.Provider.Sqlite.dll,可前往 nuget 下载"); + break; + default: throw new Exception("未指定 UseConnectionString"); + } + ret = Activator.CreateInstance(type, new object[] { _masterConnectionString, _slaveConnectionString }) as IFreeSql; + if (ret != null) + { + ret.CodeFirst.IsAutoSyncStructure = _isAutoSyncStructure; - ret.CodeFirst.IsSyncStructureToLower = _isSyncStructureToLower; - ret.CodeFirst.IsSyncStructureToUpper = _isSyncStructureToUpper; - ret.CodeFirst.IsConfigEntityFromDbFirst = _isConfigEntityFromDbFirst; - ret.CodeFirst.IsNoneCommandParameter = _isNoneCommandParameter; - ret.CodeFirst.IsLazyLoading = _isLazyLoading; - var ado = ret.Ado as Internal.CommonProvider.AdoProvider; - ado.AopCommandExecuting += _aopCommandExecuting; - ado.AopCommandExecuted += _aopCommandExecuted; + ret.CodeFirst.IsSyncStructureToLower = _isSyncStructureToLower; + ret.CodeFirst.IsSyncStructureToUpper = _isSyncStructureToUpper; + ret.CodeFirst.IsConfigEntityFromDbFirst = _isConfigEntityFromDbFirst; + ret.CodeFirst.IsNoneCommandParameter = _isNoneCommandParameter; + ret.CodeFirst.IsLazyLoading = _isLazyLoading; + var ado = ret.Ado as Internal.CommonProvider.AdoProvider; + ado.AopCommandExecuting += _aopCommandExecuting; + ado.AopCommandExecuted += _aopCommandExecuted; - //添加实体属性名全局AOP转换处理 - if (_entityPropertyConvertType != StringConvertType.None) { - switch (_entityPropertyConvertType) { - case StringConvertType.Lower: - ret.Aop.ConfigEntityProperty = (s, e) => { - e.ModifyResult.Name = e.Property.Name.ToLower(); - }; - break; - case StringConvertType.Upper: - ret.Aop.ConfigEntityProperty = (s, e) => { - e.ModifyResult.Name = e.Property.Name.ToUpper(); - }; - break; - case StringConvertType.PascalCaseToUnderscore: - ret.Aop.ConfigEntityProperty = (s, e) => { - e.ModifyResult.Name = StringUtils.PascalCaseToUnderScore(e.Property.Name); - }; - break; - case StringConvertType.PascalCaseToUnderscoreWithLower: - ret.Aop.ConfigEntityProperty = (s, e) => { - e.ModifyResult.Name = StringUtils.PascalCaseToUnderScore(e.Property.Name).ToLower(); - }; - break; - case StringConvertType.PascalCaseToUnderscoreWithUpper: - ret.Aop.ConfigEntityProperty = (s, e) => { - e.ModifyResult.Name = StringUtils.PascalCaseToUnderScore(e.Property.Name).ToUpper(); - }; - break; - default: - break; - } - } - } + //添加实体属性名全局AOP转换处理 + if (_entityPropertyConvertType != StringConvertType.None) + { + switch (_entityPropertyConvertType) + { + case StringConvertType.Lower: + ret.Aop.ConfigEntityProperty = (s, e) => + { + e.ModifyResult.Name = e.Property.Name.ToLower(); + }; + break; + case StringConvertType.Upper: + ret.Aop.ConfigEntityProperty = (s, e) => + { + e.ModifyResult.Name = e.Property.Name.ToUpper(); + }; + break; + case StringConvertType.PascalCaseToUnderscore: + ret.Aop.ConfigEntityProperty = (s, e) => + { + e.ModifyResult.Name = StringUtils.PascalCaseToUnderScore(e.Property.Name); + }; + break; + case StringConvertType.PascalCaseToUnderscoreWithLower: + ret.Aop.ConfigEntityProperty = (s, e) => + { + e.ModifyResult.Name = StringUtils.PascalCaseToUnderScore(e.Property.Name).ToLower(); + }; + break; + case StringConvertType.PascalCaseToUnderscoreWithUpper: + ret.Aop.ConfigEntityProperty = (s, e) => + { + e.ModifyResult.Name = StringUtils.PascalCaseToUnderScore(e.Property.Name).ToUpper(); + }; + break; + default: + break; + } + } + } - return ret; - } - } + return ret; + } + } } diff --git a/FreeSql/FreeUtil.cs b/FreeSql/FreeUtil.cs index 11a82798..d6007789 100644 --- a/FreeSql/FreeUtil.cs +++ b/FreeSql/FreeUtil.cs @@ -6,29 +6,31 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; -public static class FreeUtil { +public static class FreeUtil +{ - private static DateTime dt1970 = new DateTime(1970, 1, 1); - private static ThreadLocal rnd = new ThreadLocal(() => new Random()); - private static readonly int __staticMachine = ((0x00ffffff & Environment.MachineName.GetHashCode()) + + private static DateTime dt1970 = new DateTime(1970, 1, 1); + private static ThreadLocal rnd = new ThreadLocal(() => new Random()); + private static readonly int __staticMachine = ((0x00ffffff & Environment.MachineName.GetHashCode()) + #if NETSTANDARD1_5 || NETSTANDARD1_6 1 #else - AppDomain.CurrentDomain.Id + AppDomain.CurrentDomain.Id #endif - ) & 0x00ffffff; - private static readonly int __staticPid = Process.GetCurrentProcess().Id; - private static int __staticIncrement = rnd.Value.Next(); - /// - /// 生成类似Mongodb的ObjectId有序、不重复Guid - /// - /// - public static Guid NewMongodbId() { - var now = DateTime.Now; - var uninxtime = (int)now.Subtract(dt1970).TotalSeconds; - int increment = Interlocked.Increment(ref __staticIncrement) & 0x00ffffff; - var rand = rnd.Value.Next(0, int.MaxValue); - var guid = $"{uninxtime.ToString("x8").PadLeft(8, '0')}{__staticMachine.ToString("x8").PadLeft(8, '0').Substring(2, 6)}{__staticPid.ToString("x8").PadLeft(8, '0').Substring(6, 2)}{increment.ToString("x8").PadLeft(8, '0')}{rand.ToString("x8").PadLeft(8, '0')}"; - return Guid.Parse(guid); - } + ) & 0x00ffffff; + private static readonly int __staticPid = Process.GetCurrentProcess().Id; + private static int __staticIncrement = rnd.Value.Next(); + /// + /// 生成类似Mongodb的ObjectId有序、不重复Guid + /// + /// + public static Guid NewMongodbId() + { + var now = DateTime.Now; + var uninxtime = (int)now.Subtract(dt1970).TotalSeconds; + int increment = Interlocked.Increment(ref __staticIncrement) & 0x00ffffff; + var rand = rnd.Value.Next(0, int.MaxValue); + var guid = $"{uninxtime.ToString("x8").PadLeft(8, '0')}{__staticMachine.ToString("x8").PadLeft(8, '0').Substring(2, 6)}{__staticPid.ToString("x8").PadLeft(8, '0').Substring(6, 2)}{increment.ToString("x8").PadLeft(8, '0')}{rand.ToString("x8").PadLeft(8, '0')}"; + return Guid.Parse(guid); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/IDelete.cs b/FreeSql/Interface/Curd/IDelete.cs index 5218d0ce..b038153f 100644 --- a/FreeSql/Interface/Curd/IDelete.cs +++ b/FreeSql/Interface/Curd/IDelete.cs @@ -4,90 +4,92 @@ using System.Data.Common; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface IDelete where T1 : class { +namespace FreeSql +{ + public interface IDelete where T1 : class + { - /// - /// 指定事务对象 - /// - /// - /// - IDelete WithTransaction(DbTransaction transaction); - /// - /// 指定事务对象 - /// - /// - /// - IDelete WithConnection(DbConnection connection); + /// + /// 指定事务对象 + /// + /// + /// + IDelete WithTransaction(DbTransaction transaction); + /// + /// 指定事务对象 + /// + /// + /// + IDelete WithConnection(DbConnection connection); - /// - /// lambda表达式条件,仅支持实体基础成员(不包含导航对象) - /// - /// lambda表达式条件 - /// - IDelete Where(Expression> exp); - /// - /// 原生sql语法条件,Where("id = ?id", new { id = 1 }) - /// - /// sql语法条件 - /// 参数 - /// - IDelete Where(string sql, object parms = null); - /// - /// 传入实体,将主键作为条件 - /// - /// 实体 - /// - IDelete Where(T1 item); - /// - /// 传入实体集合,将主键作为条件 - /// - /// 实体集合 - /// - IDelete Where(IEnumerable items); - /// - /// 子查询是否存在 - /// - /// - /// 子查询 - /// 不存在 - /// - IDelete WhereExists(ISelect select, bool notExists = false) where TEntity2 : class; - /// - /// 传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} - /// - /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 - /// - IDelete WhereDynamic(object dywhere); + /// + /// lambda表达式条件,仅支持实体基础成员(不包含导航对象) + /// + /// lambda表达式条件 + /// + IDelete Where(Expression> exp); + /// + /// 原生sql语法条件,Where("id = ?id", new { id = 1 }) + /// + /// sql语法条件 + /// 参数 + /// + IDelete Where(string sql, object parms = null); + /// + /// 传入实体,将主键作为条件 + /// + /// 实体 + /// + IDelete Where(T1 item); + /// + /// 传入实体集合,将主键作为条件 + /// + /// 实体集合 + /// + IDelete Where(IEnumerable items); + /// + /// 子查询是否存在 + /// + /// + /// 子查询 + /// 不存在 + /// + IDelete WhereExists(ISelect select, bool notExists = false) where TEntity2 : class; + /// + /// 传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} + /// + /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 + /// + IDelete WhereDynamic(object dywhere); - /// - /// 设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名; - /// - /// - /// - IDelete AsTable(Func tableRule); - /// - /// 动态Type,在使用 Delete<object> 后使用本方法,指定实体类型 - /// - /// - /// - IDelete AsType(Type entityType); - /// - /// 返回即将执行的SQL语句 - /// - /// - string ToSql(); - /// - /// 执行SQL语句,返回影响的行数 - /// - /// - int ExecuteAffrows(); - Task ExecuteAffrowsAsync(); - /// - /// 执行SQL语句,返回被删除的记录 - /// - /// - List ExecuteDeleted(); - Task> ExecuteDeletedAsync(); - } + /// + /// 设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名; + /// + /// + /// + IDelete AsTable(Func tableRule); + /// + /// 动态Type,在使用 Delete<object> 后使用本方法,指定实体类型 + /// + /// + /// + IDelete AsType(Type entityType); + /// + /// 返回即将执行的SQL语句 + /// + /// + string ToSql(); + /// + /// 执行SQL语句,返回影响的行数 + /// + /// + int ExecuteAffrows(); + Task ExecuteAffrowsAsync(); + /// + /// 执行SQL语句,返回被删除的记录 + /// + /// + List ExecuteDeleted(); + Task> ExecuteDeletedAsync(); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/IInsert.cs b/FreeSql/Interface/Curd/IInsert.cs index 90c0239d..09184d67 100644 --- a/FreeSql/Interface/Curd/IInsert.cs +++ b/FreeSql/Interface/Curd/IInsert.cs @@ -4,94 +4,96 @@ using System.Data.Common; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface IInsert where T1 : class { +namespace FreeSql +{ + public interface IInsert where T1 : class + { - /// - /// 指定事务对象 - /// - /// - /// - IInsert WithTransaction(DbTransaction transaction); - /// - /// 指定事务对象 - /// - /// - /// - IInsert WithConnection(DbConnection connection); + /// + /// 指定事务对象 + /// + /// + /// + IInsert WithTransaction(DbTransaction transaction); + /// + /// 指定事务对象 + /// + /// + /// + IInsert WithConnection(DbConnection connection); - /// - /// 追加准备插入的实体 - /// - /// 实体 - /// - IInsert AppendData(T1 source); - /// - /// 追加准备插入的实体 - /// - /// 实体 - /// - IInsert AppendData(T1[] source); - /// - /// 追加准备插入的实体集合 - /// - /// 实体集合 - /// - IInsert AppendData(IEnumerable source); + /// + /// 追加准备插入的实体 + /// + /// 实体 + /// + IInsert AppendData(T1 source); + /// + /// 追加准备插入的实体 + /// + /// 实体 + /// + IInsert AppendData(T1[] source); + /// + /// 追加准备插入的实体集合 + /// + /// 实体集合 + /// + IInsert AppendData(IEnumerable source); - /// - /// 只插入的列,InsertColumns(a => a.Name) | InsertColumns(a => new{a.Name,a.Time}) | InsertColumns(a => new[]{"name","time"}) - /// - /// lambda选择列 - /// - IInsert InsertColumns(Expression> columns); - /// - /// 忽略的列,IgnoreColumns(a => a.Name) | IgnoreColumns(a => new{a.Name,a.Time}) | IgnoreColumns(a => new[]{"name","time"}) - /// - /// lambda选择列 - /// - IInsert IgnoreColumns(Expression> columns); + /// + /// 只插入的列,InsertColumns(a => a.Name) | InsertColumns(a => new{a.Name,a.Time}) | InsertColumns(a => new[]{"name","time"}) + /// + /// lambda选择列 + /// + IInsert InsertColumns(Expression> columns); + /// + /// 忽略的列,IgnoreColumns(a => a.Name) | IgnoreColumns(a => new{a.Name,a.Time}) | IgnoreColumns(a => new[]{"name","time"}) + /// + /// lambda选择列 + /// + IInsert IgnoreColumns(Expression> columns); - /// - /// 不使用参数化,可通过 IFreeSql.CodeFirst.IsNotCommandParameter 全局性设置 - /// - /// - IInsert NoneParameter(); + /// + /// 不使用参数化,可通过 IFreeSql.CodeFirst.IsNotCommandParameter 全局性设置 + /// + /// + IInsert NoneParameter(); - /// - /// 设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名; - /// - /// - /// - IInsert AsTable(Func tableRule); - /// - /// 动态Type,在使用 Insert<object> 后使用本方法,指定实体类型 - /// - /// - /// - IInsert AsType(Type entityType); - /// - /// 返回即将执行的SQL语句 - /// - /// - string ToSql(); - /// - /// 执行SQL语句,返回影响的行数 - /// - /// - int ExecuteAffrows(); - Task ExecuteAffrowsAsync(); - /// - /// 执行SQL语句,返回自增值 - /// - /// - long ExecuteIdentity(); - Task ExecuteIdentityAsync(); - /// - /// 执行SQL语句,返回插入后的记录 - /// - /// - List ExecuteInserted(); - Task> ExecuteInsertedAsync(); - } + /// + /// 设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名; + /// + /// + /// + IInsert AsTable(Func tableRule); + /// + /// 动态Type,在使用 Insert<object> 后使用本方法,指定实体类型 + /// + /// + /// + IInsert AsType(Type entityType); + /// + /// 返回即将执行的SQL语句 + /// + /// + string ToSql(); + /// + /// 执行SQL语句,返回影响的行数 + /// + /// + int ExecuteAffrows(); + Task ExecuteAffrowsAsync(); + /// + /// 执行SQL语句,返回自增值 + /// + /// + long ExecuteIdentity(); + Task ExecuteIdentityAsync(); + /// + /// 执行SQL语句,返回插入后的记录 + /// + /// + List ExecuteInserted(); + Task> ExecuteInsertedAsync(); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ILinqToSql.cs b/FreeSql/Interface/Curd/ISelect/ILinqToSql.cs index 9d0bea94..bba2d4e0 100644 --- a/FreeSql/Interface/Curd/ISelect/ILinqToSql.cs +++ b/FreeSql/Interface/Curd/ISelect/ILinqToSql.cs @@ -3,27 +3,29 @@ using System.Collections.Generic; using System.Linq.Expressions; using System.Text; -namespace FreeSql { - public interface ILinqToSql where T1 : class { - /// - /// 【linq to sql】专用方法,不建议直接使用 - /// - ISelect Select(Expression> select) where TReturn : class; - /// - /// 【linq to sql】专用方法,不建议直接使用 - /// - ISelect Join(ISelect inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression> resultSelector) where TInner : class where TResult : class; - /// - /// 【linq to sql】专用方法,不建议直接使用 - /// - ISelect GroupJoin(ISelect inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression, TResult>> resultSelector) where TInner : class where TResult : class; - /// - /// 【linq to sql】专用方法,不建议直接使用 - /// - ISelect DefaultIfEmpty(); - /// - /// 【linq to sql】专用方法,不建议直接使用 - /// - ISelect SelectMany(Expression>> collectionSelector, Expression> resultSelector) where TCollection : class where TResult : class; - } +namespace FreeSql +{ + public interface ILinqToSql where T1 : class + { + /// + /// 【linq to sql】专用方法,不建议直接使用 + /// + ISelect Select(Expression> select) where TReturn : class; + /// + /// 【linq to sql】专用方法,不建议直接使用 + /// + ISelect Join(ISelect inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression> resultSelector) where TInner : class where TResult : class; + /// + /// 【linq to sql】专用方法,不建议直接使用 + /// + ISelect GroupJoin(ISelect inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression, TResult>> resultSelector) where TInner : class where TResult : class; + /// + /// 【linq to sql】专用方法,不建议直接使用 + /// + ISelect DefaultIfEmpty(); + /// + /// 【linq to sql】专用方法,不建议直接使用 + /// + ISelect SelectMany(Expression>> collectionSelector, Expression> resultSelector) where TCollection : class where TResult : class; + } } diff --git a/FreeSql/Interface/Curd/ISelect/ISelect0.cs b/FreeSql/Interface/Curd/ISelect/ISelect0.cs index d162d72a..8e1567b3 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect0.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect0.cs @@ -6,255 +6,257 @@ using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect0 { +namespace FreeSql +{ + public interface ISelect0 + { - /// - /// 指定事务对象 - /// - /// - /// - TSelect WithTransaction(DbTransaction transaction); - /// - /// 指定连接对象 - /// - /// - /// - TSelect WithConnection(DbConnection connection); + /// + /// 指定事务对象 + /// + /// + /// + TSelect WithTransaction(DbTransaction transaction); + /// + /// 指定连接对象 + /// + /// + /// + TSelect WithConnection(DbConnection connection); - /// - /// 审核或跟踪 ToList 即将返回的数据 - /// - /// - /// - TSelect TrackToList(Action action); + /// + /// 审核或跟踪 ToList 即将返回的数据 + /// + /// + /// + TSelect TrackToList(Action action); - /// - /// 执行SQL查询,返回 DataTable - /// - /// - DataTable ToDataTable(string field = null); - Task ToDataTableAsync(string field = null); + /// + /// 执行SQL查询,返回 DataTable + /// + /// + DataTable ToDataTable(string field = null); + Task ToDataTableAsync(string field = null); - /// - /// 执行SQL查询,返回 T1 实体所有字段的记录,记录不存在时返回 Count 为 0 的列表 - /// - /// false: 返回 2级 LeftJoin/InnerJoin/RightJoin 对象;true: 返回所有 LeftJoin/InnerJoin/RightJoin 的导航数据 - /// - List ToList(bool includeNestedMembers = false); - Task> ToListAsync(bool includeNestedMembers = false); - /// - /// 执行SQL查询,返回 field 指定字段的记录,并以元组或基础类型(int,string,long)接收,记录不存在时返回 Count 为 0 的列表 - /// - /// - /// - /// - List ToList(string field); - Task> ToListAsync(string field); - /// - /// 执行SQL查询,返回 T1 实体所有字段的第一条记录,记录不存在时返回 null - /// - /// - T1 ToOne(); - Task ToOneAsync(); + /// + /// 执行SQL查询,返回 T1 实体所有字段的记录,记录不存在时返回 Count 为 0 的列表 + /// + /// false: 返回 2级 LeftJoin/InnerJoin/RightJoin 对象;true: 返回所有 LeftJoin/InnerJoin/RightJoin 的导航数据 + /// + List ToList(bool includeNestedMembers = false); + Task> ToListAsync(bool includeNestedMembers = false); + /// + /// 执行SQL查询,返回 field 指定字段的记录,并以元组或基础类型(int,string,long)接收,记录不存在时返回 Count 为 0 的列表 + /// + /// + /// + /// + List ToList(string field); + Task> ToListAsync(string field); + /// + /// 执行SQL查询,返回 T1 实体所有字段的第一条记录,记录不存在时返回 null + /// + /// + T1 ToOne(); + Task ToOneAsync(); - /// - /// 执行SQL查询,返回 T1 实体所有字段的第一条记录,记录不存在时返回 null - /// - /// - T1 First(); - Task FirstAsync(); + /// + /// 执行SQL查询,返回 T1 实体所有字段的第一条记录,记录不存在时返回 null + /// + /// + T1 First(); + Task FirstAsync(); - /// - /// 设置表名规则,可用于分库/分表,参数1:实体类型;参数2:默认表名;返回值:新表名; - /// - /// - /// - TSelect AsTable(Func tableRule); - /// - /// 动态Type,在使用 Select<object> 后使用本方法,指定实体类型 - /// - /// - /// - TSelect AsType(Type entityType); - /// - /// 返回即将执行的SQL语句 - /// - /// 指定字段 - /// - string ToSql(string field = null); - /// - /// 执行SQL查询,是否有记录 - /// - /// - bool Any(); - Task AnyAsync(); + /// + /// 设置表名规则,可用于分库/分表,参数1:实体类型;参数2:默认表名;返回值:新表名; + /// + /// + /// + TSelect AsTable(Func tableRule); + /// + /// 动态Type,在使用 Select<object> 后使用本方法,指定实体类型 + /// + /// + /// + TSelect AsType(Type entityType); + /// + /// 返回即将执行的SQL语句 + /// + /// 指定字段 + /// + string ToSql(string field = null); + /// + /// 执行SQL查询,是否有记录 + /// + /// + bool Any(); + Task AnyAsync(); - /// - /// 查询的记录数量 - /// - /// - long Count(); - Task CountAsync(); - /// - /// 查询的记录数量,以参数out形式返回 - /// - /// 返回的变量 - /// - TSelect Count(out long count); + /// + /// 查询的记录数量 + /// + /// + long Count(); + Task CountAsync(); + /// + /// 查询的记录数量,以参数out形式返回 + /// + /// 返回的变量 + /// + TSelect Count(out long count); - /// - /// 指定从主库查询(默认查询从库) - /// - /// - TSelect Master(); + /// + /// 指定从主库查询(默认查询从库) + /// + /// + TSelect Master(); - /// - /// 左联查询,使用导航属性自动生成SQL - /// - /// 表达式 - /// - TSelect LeftJoin(Expression> exp); - /// - /// 联接查询,使用导航属性自动生成SQL - /// - /// 表达式 - /// - TSelect InnerJoin(Expression> exp); - /// - /// 右联查询,使用导航属性自动生成SQL - /// - /// 表达式 - /// - TSelect RightJoin(Expression> exp); - /// - /// 左联查询,指定关联的实体类型 - /// - /// 关联的实体类型 - /// 表达式 - /// - TSelect LeftJoin(Expression> exp); - /// - /// 联接查询,指定关联的实体类型 - /// - /// 关联的实体类型 - /// 表达式 - /// - TSelect InnerJoin(Expression> exp); - /// - /// 右联查询,指定关联的实体类型 - /// - /// 关联的实体类型 - /// 表达式 - /// - TSelect RightJoin(Expression> exp); + /// + /// 左联查询,使用导航属性自动生成SQL + /// + /// 表达式 + /// + TSelect LeftJoin(Expression> exp); + /// + /// 联接查询,使用导航属性自动生成SQL + /// + /// 表达式 + /// + TSelect InnerJoin(Expression> exp); + /// + /// 右联查询,使用导航属性自动生成SQL + /// + /// 表达式 + /// + TSelect RightJoin(Expression> exp); + /// + /// 左联查询,指定关联的实体类型 + /// + /// 关联的实体类型 + /// 表达式 + /// + TSelect LeftJoin(Expression> exp); + /// + /// 联接查询,指定关联的实体类型 + /// + /// 关联的实体类型 + /// 表达式 + /// + TSelect InnerJoin(Expression> exp); + /// + /// 右联查询,指定关联的实体类型 + /// + /// 关联的实体类型 + /// 表达式 + /// + TSelect RightJoin(Expression> exp); - /// - /// 左联查询,使用原生sql语法,LeftJoin("type b on b.id = a.id and b.clicks > ?clicks", new { clicks = 1 }) - /// - /// sql语法条件 - /// 参数 - /// - TSelect LeftJoin(string sql, object parms = null); - /// - /// 联接查询,使用原生sql语法,InnerJoin("type b on b.id = a.id and b.clicks > ?clicks", new { clicks = 1 }) - /// - /// sql语法条件 - /// 参数 - /// - TSelect InnerJoin(string sql, object parms = null); - /// - /// 右联查询,使用原生sql语法,RightJoin("type b on b.id = a.id and b.clicks > ?clicks", new { clicks = 1 }) - /// - /// sql语法条件 - /// 参数 - /// - TSelect RightJoin(string sql, object parms = null); + /// + /// 左联查询,使用原生sql语法,LeftJoin("type b on b.id = a.id and b.clicks > ?clicks", new { clicks = 1 }) + /// + /// sql语法条件 + /// 参数 + /// + TSelect LeftJoin(string sql, object parms = null); + /// + /// 联接查询,使用原生sql语法,InnerJoin("type b on b.id = a.id and b.clicks > ?clicks", new { clicks = 1 }) + /// + /// sql语法条件 + /// 参数 + /// + TSelect InnerJoin(string sql, object parms = null); + /// + /// 右联查询,使用原生sql语法,RightJoin("type b on b.id = a.id and b.clicks > ?clicks", new { clicks = 1 }) + /// + /// sql语法条件 + /// 参数 + /// + TSelect RightJoin(string sql, object parms = null); - /// - /// 原生sql语法条件,Where("id = ?id", new { id = 1 }) - /// - /// sql语法条件 - /// 参数 - /// - TSelect Where(string sql, object parms = null); - /// - /// 原生sql语法条件,WhereIf(true, "id = ?id", new { id = 1 }) - /// - /// true 时生效 - /// sql语法条件 - /// 参数 - /// - TSelect WhereIf(bool condition, string sql, object parms = null); + /// + /// 原生sql语法条件,Where("id = ?id", new { id = 1 }) + /// + /// sql语法条件 + /// 参数 + /// + TSelect Where(string sql, object parms = null); + /// + /// 原生sql语法条件,WhereIf(true, "id = ?id", new { id = 1 }) + /// + /// true 时生效 + /// sql语法条件 + /// 参数 + /// + TSelect WhereIf(bool condition, string sql, object parms = null); - /// - /// 按原生sql语法分组,GroupBy("concat(name, ?cc)", new { cc = 1 }) - /// - /// sql语法 - /// 参数 - /// - TSelect GroupBy(string sql, object parms = null); - /// - /// 按原生sql语法聚合条件过滤,Having("count(name) = ?cc", new { cc = 1 }) - /// - /// sql语法条件 - /// 参数 - /// - TSelect Having(string sql, object parms = null); + /// + /// 按原生sql语法分组,GroupBy("concat(name, ?cc)", new { cc = 1 }) + /// + /// sql语法 + /// 参数 + /// + TSelect GroupBy(string sql, object parms = null); + /// + /// 按原生sql语法聚合条件过滤,Having("count(name) = ?cc", new { cc = 1 }) + /// + /// sql语法条件 + /// 参数 + /// + TSelect Having(string sql, object parms = null); - /// - /// 按原生sql语法排序,OrderBy("count(name) + ?cc desc", new { cc = 1 }) - /// - /// sql语法 - /// 参数 - /// - TSelect OrderBy(string sql, object parms = null); - /// - /// 按原生sql语法排序,OrderBy(true, "count(name) + ?cc desc", new { cc = 1 }) - /// - /// true 时生效 - /// sql语法 - /// 参数 - /// - TSelect OrderBy(bool condition, string sql, object parms = null); + /// + /// 按原生sql语法排序,OrderBy("count(name) + ?cc desc", new { cc = 1 }) + /// + /// sql语法 + /// 参数 + /// + TSelect OrderBy(string sql, object parms = null); + /// + /// 按原生sql语法排序,OrderBy(true, "count(name) + ?cc desc", new { cc = 1 }) + /// + /// true 时生效 + /// sql语法 + /// 参数 + /// + TSelect OrderBy(bool condition, string sql, object parms = null); - /// - /// 查询向后偏移行数 - /// - /// - /// - TSelect Skip(int offset); - /// - /// 查询向后偏移行数 - /// - /// 行数 - /// - TSelect Offset(int offset); - /// - /// 查询多少条数据 - /// - /// - /// - TSelect Limit(int limit); - /// - /// 查询多少条数据 - /// - /// - /// - TSelect Take(int limit); + /// + /// 查询向后偏移行数 + /// + /// + /// + TSelect Skip(int offset); + /// + /// 查询向后偏移行数 + /// + /// 行数 + /// + TSelect Offset(int offset); + /// + /// 查询多少条数据 + /// + /// + /// + TSelect Limit(int limit); + /// + /// 查询多少条数据 + /// + /// + /// + TSelect Take(int limit); - /// - /// 分页 - /// - /// 第几页 - /// 每页多少 - /// - TSelect Page(int pageNumber, int pageSize); + /// + /// 分页 + /// + /// 第几页 + /// 每页多少 + /// + TSelect Page(int pageNumber, int pageSize); - /// - /// 查询数据前,去重 - /// - /// - TSelect Distinct(); - } + /// + /// 查询数据前,去重 + /// + /// + TSelect Distinct(); + } } diff --git a/FreeSql/Interface/Curd/ISelect/ISelect1.cs b/FreeSql/Interface/Curd/ISelect/ISelect1.cs index 0c5f2ce2..ffc07e50 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect1.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect1.cs @@ -4,325 +4,327 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1>, ILinqToSql where T1 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1>, ILinqToSql where T1 : class + { - /// - /// 执行SQL查询,是否有记录 - /// - /// lambda表达式 - /// - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + /// + /// 执行SQL查询,是否有记录 + /// + /// lambda表达式 + /// + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - /// - /// 执行SQL查询,返回 DataTable - /// - /// - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + /// + /// 执行SQL查询,返回 DataTable + /// + /// + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - /// - /// 执行SQL查询,返回指定字段的记录,记录不存在时返回 Count 为 0 的列表 - /// - /// 返回类型 - /// 选择列 - /// - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - /// - /// 执行SQL查询,返回 TDto 映射的字段,记录不存在时返回 Count 为 0 的列表 - /// - /// - /// - List ToList(); - Task> ToListAsync(); + /// + /// 执行SQL查询,返回指定字段的记录,记录不存在时返回 Count 为 0 的列表 + /// + /// 返回类型 + /// 选择列 + /// + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + /// + /// 执行SQL查询,返回 TDto 映射的字段,记录不存在时返回 Count 为 0 的列表 + /// + /// + /// + List ToList(); + Task> ToListAsync(); - /// - /// 执行SQL查询,返回指定字段的记录的第一条记录,记录不存在时返回 TReturn 默认值 - /// - /// 返回类型 - /// 选择列 - /// - TReturn ToOne(Expression> select); - Task ToOneAsync(Expression> select); + /// + /// 执行SQL查询,返回指定字段的记录的第一条记录,记录不存在时返回 TReturn 默认值 + /// + /// 返回类型 + /// 选择列 + /// + TReturn ToOne(Expression> select); + Task ToOneAsync(Expression> select); - /// - /// 执行SQL查询,返回指定字段的记录的第一条记录,记录不存在时返回 TReturn 默认值 - /// - /// 返回类型 - /// 选择列 - /// - TReturn First(Expression> select); - Task FirstAsync(Expression> select); + /// + /// 执行SQL查询,返回指定字段的记录的第一条记录,记录不存在时返回 TReturn 默认值 + /// + /// 返回类型 + /// 选择列 + /// + TReturn First(Expression> select); + Task FirstAsync(Expression> select); - /// - /// 返回即将执行的SQL语句 - /// - /// 返回类型 - /// 选择列 - /// - string ToSql(Expression> select); + /// + /// 返回即将执行的SQL语句 + /// + /// 返回类型 + /// 选择列 + /// + string ToSql(Expression> select); - /// - /// 执行SQL查询,返回指定字段的聚合结果 - /// - /// - /// - /// - TReturn ToAggregate(Expression, TReturn>> select); - Task ToAggregateAsync(Expression, TReturn>> select); + /// + /// 执行SQL查询,返回指定字段的聚合结果 + /// + /// + /// + /// + TReturn ToAggregate(Expression, TReturn>> select); + Task ToAggregateAsync(Expression, TReturn>> select); - /// - /// 求和 - /// - /// 返回类型 - /// 列 - /// - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - /// - /// 最小值 - /// - /// 返回类型 - /// 列 - /// - TMember Min(Expression> column); - Task MinAsync(Expression> column); - /// - /// 最大值 - /// - /// 返回类型 - /// 列 - /// - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - /// - /// 平均值 - /// - /// 返回类型 - /// 列 - /// - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + /// + /// 求和 + /// + /// 返回类型 + /// 列 + /// + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + /// + /// 最小值 + /// + /// 返回类型 + /// 列 + /// + TMember Min(Expression> column); + Task MinAsync(Expression> column); + /// + /// 最大值 + /// + /// 返回类型 + /// 列 + /// + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + /// + /// 平均值 + /// + /// 返回类型 + /// 列 + /// + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - /// - /// 指定别名 - /// - /// 别名 - /// - ISelect As(string alias = "a"); + /// + /// 指定别名 + /// + /// 别名 + /// + ISelect As(string alias = "a"); - /// - /// 多表查询 - /// - /// - /// - /// - ISelect From(Expression, T2, ISelectFromExpression>> exp) where T2 : class; - /// - /// 多表查询 - /// - /// - /// - /// - /// - ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) where T2 : class where T3 : class; - /// - /// 多表查询 - /// - /// - /// - /// - /// - /// - ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class; - /// - /// 多表查询 - /// - /// - /// - /// - /// - /// - /// - ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class; - /// - /// 多表查询 - /// - /// - /// - /// - /// - /// - /// - /// - ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class; - /// - /// 多表查询 - /// - /// - /// - /// - /// - /// - /// - /// - /// - ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class; - /// - /// 多表查询 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class; - /// - /// 多表查询 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class; - /// - /// 多表查询 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class; + /// + /// 多表查询 + /// + /// + /// + /// + ISelect From(Expression, T2, ISelectFromExpression>> exp) where T2 : class; + /// + /// 多表查询 + /// + /// + /// + /// + /// + ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) where T2 : class where T3 : class; + /// + /// 多表查询 + /// + /// + /// + /// + /// + /// + ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class; + /// + /// 多表查询 + /// + /// + /// + /// + /// + /// + /// + ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class; + /// + /// 多表查询 + /// + /// + /// + /// + /// + /// + /// + /// + ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class; + /// + /// 多表查询 + /// + /// + /// + /// + /// + /// + /// + /// + /// + ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class; + /// + /// 多表查询 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class; + /// + /// 多表查询 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class; + /// + /// 多表查询 + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class; - /// - /// 查询条件,Where(a => a.Id > 10),支持导航对象查询,Where(a => a.Author.Email == "2881099@qq.com") - /// - /// lambda表达式 - /// - ISelect Where(Expression> exp); - /// - /// 查询条件,Where(true, a => a.Id > 10),支导航对象查询,Where(true, a => a.Author.Email == "2881099@qq.com") - /// - /// true 时生效 - /// lambda表达式 - /// - ISelect WhereIf(bool condition, Expression> exp); - /// - /// 多表条件查询 - /// - /// - /// lambda表达式 - /// - ISelect Where(Expression> exp) where T2 : class; - /// - /// 多表条件查询 - /// - /// - /// lambda表达式 - /// - ISelect Where(Expression> exp) where T2 : class; - /// - /// 多表条件查询 - /// - /// - /// - /// lambda表达式 - /// - ISelect Where(Expression> exp) where T2 : class where T3 : class; - /// - /// 多表条件查询 - /// - /// - /// - /// - /// lambda表达式 - /// - ISelect Where(Expression> exp) where T2 : class where T3 : class where T4 : class; - /// - /// 多表条件查询 - /// - /// - /// - /// - /// lambda表达式 - /// - ISelect Where(Expression> exp) where T2 : class where T3 : class where T4 : class where T5 : class; - /// - /// 传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} - /// - /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 - /// - ISelect WhereDynamic(object dywhere); + /// + /// 查询条件,Where(a => a.Id > 10),支持导航对象查询,Where(a => a.Author.Email == "2881099@qq.com") + /// + /// lambda表达式 + /// + ISelect Where(Expression> exp); + /// + /// 查询条件,Where(true, a => a.Id > 10),支导航对象查询,Where(true, a => a.Author.Email == "2881099@qq.com") + /// + /// true 时生效 + /// lambda表达式 + /// + ISelect WhereIf(bool condition, Expression> exp); + /// + /// 多表条件查询 + /// + /// + /// lambda表达式 + /// + ISelect Where(Expression> exp) where T2 : class; + /// + /// 多表条件查询 + /// + /// + /// lambda表达式 + /// + ISelect Where(Expression> exp) where T2 : class; + /// + /// 多表条件查询 + /// + /// + /// + /// lambda表达式 + /// + ISelect Where(Expression> exp) where T2 : class where T3 : class; + /// + /// 多表条件查询 + /// + /// + /// + /// + /// lambda表达式 + /// + ISelect Where(Expression> exp) where T2 : class where T3 : class where T4 : class; + /// + /// 多表条件查询 + /// + /// + /// + /// + /// lambda表达式 + /// + ISelect Where(Expression> exp) where T2 : class where T3 : class where T4 : class where T5 : class; + /// + /// 传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} + /// + /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 + /// + ISelect WhereDynamic(object dywhere); - /// - /// 按选择的列分组,GroupBy(a => a.Name) | GroupBy(a => new{a.Name,a.Time}) - /// - /// - /// - ISelectGrouping GroupBy(Expression> exp); + /// + /// 按选择的列分组,GroupBy(a => a.Name) | GroupBy(a => new{a.Name,a.Time}) + /// + /// + /// + ISelectGrouping GroupBy(Expression> exp); - /// - /// 按列排序,OrderBy(a => a.Time) - /// - /// - /// - /// - ISelect OrderBy(Expression> column); - /// - /// 按列排序,OrderBy(true, a => a.Time) - /// - /// - /// true 时生效 - /// - /// - ISelect OrderBy(bool condition, Expression> column); - /// - /// 按列倒向排序,OrderByDescending(a => a.Time) - /// - /// 列 - /// - ISelect OrderByDescending(Expression> column); - /// - /// 按列倒向排序,OrderByDescending(true, a => a.Time) - /// - /// true 时生效 - /// 列 - /// - ISelect OrderByDescending(bool condition, Expression> column); + /// + /// 按列排序,OrderBy(a => a.Time) + /// + /// + /// + /// + ISelect OrderBy(Expression> column); + /// + /// 按列排序,OrderBy(true, a => a.Time) + /// + /// + /// true 时生效 + /// + /// + ISelect OrderBy(bool condition, Expression> column); + /// + /// 按列倒向排序,OrderByDescending(a => a.Time) + /// + /// 列 + /// + ISelect OrderByDescending(Expression> column); + /// + /// 按列倒向排序,OrderByDescending(true, a => a.Time) + /// + /// true 时生效 + /// 列 + /// + ISelect OrderByDescending(bool condition, Expression> column); - /// - /// 贪婪加载导航属性,如果查询中已经使用了 a.Parent.Parent 类似表达式,则可以无需此操作 - /// - /// - /// 选择一个导航属性 - /// - ISelect Include(Expression> navigateSelector) where TNavigate : class; - /// - /// 贪婪加载集合的导航属性,其实是分两次查询,ToList 后进行了数据重装 - /// - /// - /// 选择一个集合的导航属性,也可通过 .Where 设置临时的关系映射,还可以 .Take(5) 每个子集合只取5条 - /// 即能 ThenInclude,还可以二次过滤(这个 EFCore 做不到?) - /// - ISelect IncludeMany(Expression>> navigateSelector, Action> then = null) where TNavigate : class; - } + /// + /// 贪婪加载导航属性,如果查询中已经使用了 a.Parent.Parent 类似表达式,则可以无需此操作 + /// + /// + /// 选择一个导航属性 + /// + ISelect Include(Expression> navigateSelector) where TNavigate : class; + /// + /// 贪婪加载集合的导航属性,其实是分两次查询,ToList 后进行了数据重装 + /// + /// + /// 选择一个集合的导航属性,也可通过 .Where 设置临时的关系映射,还可以 .Take(5) 每个子集合只取5条 + /// 即能 ThenInclude,还可以二次过滤(这个 EFCore 做不到?) + /// + ISelect IncludeMany(Expression>> navigateSelector, Action> then = null) where TNavigate : class; + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect10.cs b/FreeSql/Interface/Curd/ISelect/ISelect10.cs index 0d4ef4cb..15a8f4dd 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect10.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect10.cs @@ -4,39 +4,41 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); - string ToSql(Expression> select); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect2.cs b/FreeSql/Interface/Curd/ISelect/ISelect2.cs index 3ca335e5..c13f1b71 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect2.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect2.cs @@ -4,40 +4,42 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); - string ToSql(Expression> select); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect3.cs b/FreeSql/Interface/Curd/ISelect/ISelect3.cs index ae8c0c31..0d036dd6 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect3.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect3.cs @@ -4,39 +4,41 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); - string ToSql(Expression> select); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect4.cs b/FreeSql/Interface/Curd/ISelect/ISelect4.cs index 9e0ef889..7787cf39 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect4.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect4.cs @@ -4,39 +4,41 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); - string ToSql(Expression> select); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect5.cs b/FreeSql/Interface/Curd/ISelect/ISelect5.cs index 56fde4d2..c579b50a 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect5.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect5.cs @@ -4,39 +4,41 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); - string ToSql(Expression> select); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect6.cs b/FreeSql/Interface/Curd/ISelect/ISelect6.cs index e56ed98d..05e42d96 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect6.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect6.cs @@ -4,39 +4,41 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); - string ToSql(Expression> select); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect7.cs b/FreeSql/Interface/Curd/ISelect/ISelect7.cs index 318b6ee9..25356edb 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect7.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect7.cs @@ -4,39 +4,41 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); - string ToSql(Expression> select); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect8.cs b/FreeSql/Interface/Curd/ISelect/ISelect8.cs index 55db9df2..1404be93 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect8.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect8.cs @@ -4,39 +4,41 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); - string ToSql(Expression> select); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelect9.cs b/FreeSql/Interface/Curd/ISelect/ISelect9.cs index 5546f566..b6ed09ba 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelect9.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelect9.cs @@ -4,39 +4,41 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class { +namespace FreeSql +{ + public interface ISelect : ISelect0, T1> where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class + { - bool Any(Expression> exp); - Task AnyAsync(Expression> exp); + bool Any(Expression> exp); + Task AnyAsync(Expression> exp); - DataTable ToDataTable(Expression> select); - Task ToDataTableAsync(Expression> select); + DataTable ToDataTable(Expression> select); + Task ToDataTableAsync(Expression> select); - List ToList(Expression> select); - Task> ToListAsync(Expression> select); - List ToList(); - Task> ToListAsync(); - string ToSql(Expression> select); + List ToList(Expression> select); + Task> ToListAsync(Expression> select); + List ToList(); + Task> ToListAsync(); + string ToSql(Expression> select); - TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + TReturn ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); + Task ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select); - TMember Sum(Expression> column); - Task SumAsync(Expression> column); - TMember Min(Expression> column); - Task MinAsync(Expression> column); - TMember Max(Expression> column); - Task MaxAsync(Expression> column); - TMember Avg(Expression> column); - Task AvgAsync(Expression> column); + TMember Sum(Expression> column); + Task SumAsync(Expression> column); + TMember Min(Expression> column); + Task MinAsync(Expression> column); + TMember Max(Expression> column); + Task MaxAsync(Expression> column); + TMember Avg(Expression> column); + Task AvgAsync(Expression> column); - ISelect Where(Expression> exp); - ISelect WhereIf(bool condition, Expression> exp); + ISelect Where(Expression> exp); + ISelect WhereIf(bool condition, Expression> exp); - ISelectGrouping GroupBy(Expression> exp); + ISelectGrouping GroupBy(Expression> exp); - ISelect OrderBy(Expression> column); - ISelect OrderByDescending(Expression> column); - } + ISelect OrderBy(Expression> column); + ISelect OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelectFrom.cs b/FreeSql/Interface/Curd/ISelect/ISelectFrom.cs index 9150034e..6020ae4f 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelectFrom.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelectFrom.cs @@ -2,39 +2,41 @@ using System.Collections.Generic; using System.Linq.Expressions; -namespace FreeSql { - public interface ISelectFromExpression where T1 : class { +namespace FreeSql +{ + public interface ISelectFromExpression where T1 : class + { - ISelectFromExpression LeftJoin(Expression> exp); - ISelectFromExpression InnerJoin(Expression> exp); - ISelectFromExpression RightJoin(Expression> exp); + ISelectFromExpression LeftJoin(Expression> exp); + ISelectFromExpression InnerJoin(Expression> exp); + ISelectFromExpression RightJoin(Expression> exp); - /// - /// 查询条件,Where(a => a.Id > 10),支持导航对象查询,Where(a => a.Author.Email == "2881099@qq.com") - /// - /// lambda表达式 - /// - ISelectFromExpression Where(Expression> exp); - /// - /// 查询条件,Where(true, a => a.Id > 10),支导航对象查询,Where(true, a => a.Author.Email == "2881099@qq.com") - /// - /// true 时生效 - /// lambda表达式 - /// - ISelectFromExpression WhereIf(bool condition, Expression> exp); + /// + /// 查询条件,Where(a => a.Id > 10),支持导航对象查询,Where(a => a.Author.Email == "2881099@qq.com") + /// + /// lambda表达式 + /// + ISelectFromExpression Where(Expression> exp); + /// + /// 查询条件,Where(true, a => a.Id > 10),支导航对象查询,Where(true, a => a.Author.Email == "2881099@qq.com") + /// + /// true 时生效 + /// lambda表达式 + /// + ISelectFromExpression WhereIf(bool condition, Expression> exp); - /// - /// 按列排序,OrderBy(a => a.Time) - /// - /// - /// - /// - ISelectFromExpression OrderBy(Expression> column); - /// - /// 按列倒向排序,OrderByDescending(a => a.Time) - /// - /// 列 - /// - ISelectFromExpression OrderByDescending(Expression> column); - } + /// + /// 按列排序,OrderBy(a => a.Time) + /// + /// + /// + /// + ISelectFromExpression OrderBy(Expression> column); + /// + /// 按列倒向排序,OrderByDescending(a => a.Time) + /// + /// 列 + /// + ISelectFromExpression OrderByDescending(Expression> column); + } } \ No newline at end of file diff --git a/FreeSql/Interface/Curd/ISelect/ISelectGrouping.cs b/FreeSql/Interface/Curd/ISelect/ISelectGrouping.cs index 17c8ec0f..0b52dfbf 100644 --- a/FreeSql/Interface/Curd/ISelect/ISelectGrouping.cs +++ b/FreeSql/Interface/Curd/ISelect/ISelectGrouping.cs @@ -4,128 +4,132 @@ using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; -namespace FreeSql { - public interface ISelectGrouping { - /// - /// 按聚合条件过滤,Where(a => a.Count() > 10) - /// - /// lambda表达式 - /// - ISelectGrouping Having(Expression, bool>> exp); +namespace FreeSql +{ + public interface ISelectGrouping + { + /// + /// 按聚合条件过滤,Where(a => a.Count() > 10) + /// + /// lambda表达式 + /// + ISelectGrouping Having(Expression, bool>> exp); - /// - /// 按列排序,OrderBy(a => a.Time) - /// - /// - /// - /// - ISelectGrouping OrderBy(Expression, TMember>> column); - /// - /// 按列倒向排序,OrderByDescending(a => a.Time) - /// - /// 列 - /// - ISelectGrouping OrderByDescending(Expression, TMember>> column); + /// + /// 按列排序,OrderBy(a => a.Time) + /// + /// + /// + /// + ISelectGrouping OrderBy(Expression, TMember>> column); + /// + /// 按列倒向排序,OrderByDescending(a => a.Time) + /// + /// 列 + /// + ISelectGrouping OrderByDescending(Expression, TMember>> column); - /// - /// 执行SQL查询,返回指定字段的记录,记录不存在时返回 Count 为 0 的列表 - /// - /// 返回类型 - /// 选择列 - /// - List ToList(Expression, TReturn>> select); - Task> ToListAsync(Expression, TReturn>> select); + /// + /// 执行SQL查询,返回指定字段的记录,记录不存在时返回 Count 为 0 的列表 + /// + /// 返回类型 + /// 选择列 + /// + List ToList(Expression, TReturn>> select); + Task> ToListAsync(Expression, TReturn>> select); - /// - /// 【linq to sql】专用方法,不建议直接使用 - /// - List Select(Expression, TReturn>> select); + /// + /// 【linq to sql】专用方法,不建议直接使用 + /// + List Select(Expression, TReturn>> select); - /// - /// 返回即将执行的SQL语句 - /// - /// 返回类型 - /// 选择列 - /// - string ToSql(Expression, TReturn>> select); + /// + /// 返回即将执行的SQL语句 + /// + /// 返回类型 + /// 选择列 + /// + string ToSql(Expression, TReturn>> select); - /// - /// 查询向后偏移行数 - /// - /// - /// - ISelectGrouping Skip(int offset); - /// - /// 查询向后偏移行数 - /// - /// 行数 - /// - ISelectGrouping Offset(int offset); - /// - /// 查询多少条数据 - /// - /// - /// - ISelectGrouping Limit(int limit); - /// - /// 查询多少条数据 - /// - /// - /// - ISelectGrouping Take(int limit); + /// + /// 查询向后偏移行数 + /// + /// + /// + ISelectGrouping Skip(int offset); + /// + /// 查询向后偏移行数 + /// + /// 行数 + /// + ISelectGrouping Offset(int offset); + /// + /// 查询多少条数据 + /// + /// + /// + ISelectGrouping Limit(int limit); + /// + /// 查询多少条数据 + /// + /// + /// + ISelectGrouping Take(int limit); - /// - /// 分页 - /// - /// 第几页 - /// 每页多少 - /// - ISelectGrouping Page(int pageNumber, int pageSize); - } + /// + /// 分页 + /// + /// 第几页 + /// 每页多少 + /// + ISelectGrouping Page(int pageNumber, int pageSize); + } - public interface ISelectGroupingAggregate { - /// - /// 分组的数据 - /// - TKey Key { get; set; } - /// - /// 记录总数 - /// - /// - int Count(); - /// - /// 求和 - /// - /// - /// - /// - T3 Sum(T3 column); - /// - /// 平均值 - /// - /// - /// - /// - T3 Avg(T3 column); - /// - /// 最大值 - /// - /// - /// - /// - T3 Max(T3 column); - /// - /// 最小值 - /// - /// - /// - T3 Min(T3 column); - } - public interface ISelectGroupingAggregate : ISelectGroupingAggregate { - /// - /// 所有元素 - /// - TValue Value { get; set; } - } + public interface ISelectGroupingAggregate + { + /// + /// 分组的数据 + /// + TKey Key { get; set; } + /// + /// 记录总数 + /// + /// + int Count(); + /// + /// 求和 + /// + /// + /// + /// + T3 Sum(T3 column); + /// + /// 平均值 + /// + /// + /// + /// + T3 Avg(T3 column); + /// + /// 最大值 + /// + /// + /// + /// + T3 Max(T3 column); + /// + /// 最小值 + /// + /// + /// + T3 Min(T3 column); + } + public interface ISelectGroupingAggregate : ISelectGroupingAggregate + { + /// + /// 所有元素 + /// + TValue Value { get; set; } + } } diff --git a/FreeSql/Interface/Curd/IUpdate.cs b/FreeSql/Interface/Curd/IUpdate.cs index d1708055..6e546d4d 100644 --- a/FreeSql/Interface/Curd/IUpdate.cs +++ b/FreeSql/Interface/Curd/IUpdate.cs @@ -4,159 +4,161 @@ using System.Data.Common; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql { - public interface IUpdate where T1 : class { +namespace FreeSql +{ + public interface IUpdate where T1 : class + { - /// - /// 指定事务对象 - /// - /// - /// - IUpdate WithTransaction(DbTransaction transaction); - /// - /// 指定事务对象 - /// - /// - /// - IUpdate WithConnection(DbConnection connection); + /// + /// 指定事务对象 + /// + /// + /// + IUpdate WithTransaction(DbTransaction transaction); + /// + /// 指定事务对象 + /// + /// + /// + IUpdate WithConnection(DbConnection connection); - /// - /// 不使用参数化,可通过 IFreeSql.CodeFirst.IsNotCommandParameter 全局性设置 - /// - /// - IUpdate NoneParameter(); + /// + /// 不使用参数化,可通过 IFreeSql.CodeFirst.IsNotCommandParameter 全局性设置 + /// + /// + IUpdate NoneParameter(); - /// - /// 更新数据,设置更新的实体 - /// - /// 实体 - /// - IUpdate SetSource(T1 source); - /// - /// 更新数据,设置更新的实体集合 - /// - /// 实体集合 - /// - IUpdate SetSource(IEnumerable source); - /// - /// 忽略的列,IgnoreColumns(a => a.Name) | IgnoreColumns(a => new{a.Name,a.Time}) | IgnoreColumns(a => new[]{"name","time"}) - /// - /// lambda选择列 - /// - IUpdate IgnoreColumns(Expression> columns); - /// - /// 忽略的列 - /// - /// - /// - IUpdate IgnoreColumns(string[] columns); + /// + /// 更新数据,设置更新的实体 + /// + /// 实体 + /// + IUpdate SetSource(T1 source); + /// + /// 更新数据,设置更新的实体集合 + /// + /// 实体集合 + /// + IUpdate SetSource(IEnumerable source); + /// + /// 忽略的列,IgnoreColumns(a => a.Name) | IgnoreColumns(a => new{a.Name,a.Time}) | IgnoreColumns(a => new[]{"name","time"}) + /// + /// lambda选择列 + /// + IUpdate IgnoreColumns(Expression> columns); + /// + /// 忽略的列 + /// + /// + /// + IUpdate IgnoreColumns(string[] columns); - /// - /// 指定的列,UpdateColumns(a => a.Name) | UpdateColumns(a => new{a.Name,a.Time}) | UpdateColumns(a => new[]{"name","time"}) - /// - /// lambda选择列 - /// - IUpdate UpdateColumns(Expression> columns); - /// - /// 指定的列 - /// - /// - /// - IUpdate UpdateColumns(string[] columns); + /// + /// 指定的列,UpdateColumns(a => a.Name) | UpdateColumns(a => new{a.Name,a.Time}) | UpdateColumns(a => new[]{"name","time"}) + /// + /// lambda选择列 + /// + IUpdate UpdateColumns(Expression> columns); + /// + /// 指定的列 + /// + /// + /// + IUpdate UpdateColumns(string[] columns); - /// - /// 设置列的新值,Set(a => a.Name, "newvalue") - /// - /// - /// lambda选择列 - /// 新值 - /// - IUpdate Set(Expression> column, TMember value); - /// - /// 设置列的的新值为基础上增加,格式:Set(a => a.Clicks + 1) 相当于 clicks=clicks+1 - /// - /// 指定更新,格式:Set(a => new { Clicks = a.Clicks + 1, Time = DateTime.Now }) 相当于 set clicks=clicks+1,time='2019-06-19....' - /// - /// - /// - /// - IUpdate Set(Expression> exp); - /// - /// 设置值,自定义SQL语法,SetRaw("title = ?title", new { title = "newtitle" }) - /// - /// sql语法 - /// 参数 - /// - IUpdate SetRaw(string sql, object parms = null); + /// + /// 设置列的新值,Set(a => a.Name, "newvalue") + /// + /// + /// lambda选择列 + /// 新值 + /// + IUpdate Set(Expression> column, TMember value); + /// + /// 设置列的的新值为基础上增加,格式:Set(a => a.Clicks + 1) 相当于 clicks=clicks+1 + /// + /// 指定更新,格式:Set(a => new { Clicks = a.Clicks + 1, Time = DateTime.Now }) 相当于 set clicks=clicks+1,time='2019-06-19....' + /// + /// + /// + /// + IUpdate Set(Expression> exp); + /// + /// 设置值,自定义SQL语法,SetRaw("title = ?title", new { title = "newtitle" }) + /// + /// sql语法 + /// 参数 + /// + IUpdate SetRaw(string sql, object parms = null); - /// - /// lambda表达式条件,仅支持实体基础成员(不包含导航对象) - /// - /// lambda表达式条件 - /// - IUpdate Where(Expression> exp); - /// - /// 原生sql语法条件,Where("id = ?id", new { id = 1 }) - /// - /// sql语法条件 - /// 参数 - /// - IUpdate Where(string sql, object parms = null); - /// - /// 传入实体,将主键作为条件 - /// - /// 实体 - /// - IUpdate Where(T1 item); - /// - /// 传入实体集合,将主键作为条件 - /// - /// 实体集合 - /// - IUpdate Where(IEnumerable items); - /// - /// 子查询是否存在 - /// - /// - /// 子查询 - /// 不存在 - /// - IUpdate WhereExists(ISelect select, bool notExists = false) where TEntity2 : class; - /// - /// 传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} - /// - /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 - /// - IUpdate WhereDynamic(object dywhere); + /// + /// lambda表达式条件,仅支持实体基础成员(不包含导航对象) + /// + /// lambda表达式条件 + /// + IUpdate Where(Expression> exp); + /// + /// 原生sql语法条件,Where("id = ?id", new { id = 1 }) + /// + /// sql语法条件 + /// 参数 + /// + IUpdate Where(string sql, object parms = null); + /// + /// 传入实体,将主键作为条件 + /// + /// 实体 + /// + IUpdate Where(T1 item); + /// + /// 传入实体集合,将主键作为条件 + /// + /// 实体集合 + /// + IUpdate Where(IEnumerable items); + /// + /// 子查询是否存在 + /// + /// + /// 子查询 + /// 不存在 + /// + IUpdate WhereExists(ISelect select, bool notExists = false) where TEntity2 : class; + /// + /// 传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} + /// + /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 + /// + IUpdate WhereDynamic(object dywhere); - /// - /// 设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名; - /// - /// - /// - IUpdate AsTable(Func tableRule); - /// - /// 动态Type,在使用 Update<object> 后使用本方法,指定实体类型 - /// - /// - /// - IUpdate AsType(Type entityType); - /// - /// 返回即将执行的SQL语句 - /// - /// - string ToSql(); - /// - /// 执行SQL语句,返回影响的行数 - /// - /// - int ExecuteAffrows(); - Task ExecuteAffrowsAsync(); - /// - /// 执行SQL语句,返回更新后的记录 - /// - /// - List ExecuteUpdated(); - Task> ExecuteUpdatedAsync(); - } + /// + /// 设置表名规则,可用于分库/分表,参数1:默认表名;返回值:新表名; + /// + /// + /// + IUpdate AsTable(Func tableRule); + /// + /// 动态Type,在使用 Update<object> 后使用本方法,指定实体类型 + /// + /// + /// + IUpdate AsType(Type entityType); + /// + /// 返回即将执行的SQL语句 + /// + /// + string ToSql(); + /// + /// 执行SQL语句,返回影响的行数 + /// + /// + int ExecuteAffrows(); + Task ExecuteAffrowsAsync(); + /// + /// 执行SQL语句,返回更新后的记录 + /// + /// + List ExecuteUpdated(); + Task> ExecuteUpdatedAsync(); + } } \ No newline at end of file diff --git a/FreeSql/Interface/IAdo.cs b/FreeSql/Interface/IAdo.cs index 2eb67472..a1d16be1 100644 --- a/FreeSql/Interface/IAdo.cs +++ b/FreeSql/Interface/IAdo.cs @@ -7,385 +7,387 @@ using System.Data.Common; using System.Text; using System.Threading.Tasks; -namespace FreeSql { - public partial interface IAdo { - /// - /// 主库连接池 - /// - ObjectPool MasterPool { get; } - /// - /// 从库连接池 - /// - List> SlavePools { get; } - /// - /// 监视数据库命令对象(执行前,调试) - /// - Action AopCommandExecuting { get; set; } - /// - /// 监视数据库命令对象(执行后,用于监视执行性能) - /// - Action AopCommandExecuted { get; set; } - /// - /// 数据库类型 - /// - DataType DataType { get; } +namespace FreeSql +{ + public partial interface IAdo + { + /// + /// 主库连接池 + /// + ObjectPool MasterPool { get; } + /// + /// 从库连接池 + /// + List> SlavePools { get; } + /// + /// 监视数据库命令对象(执行前,调试) + /// + Action AopCommandExecuting { get; set; } + /// + /// 监视数据库命令对象(执行后,用于监视执行性能) + /// + Action AopCommandExecuted { get; set; } + /// + /// 数据库类型 + /// + DataType DataType { get; } - #region 事务 - /// - /// 开启事务(不支持异步),60秒未执行完将自动提交 - /// - /// 事务体 () => {} - void Transaction(Action handler); - /// - /// 开启事务(不支持异步) - /// - /// 事务体 () => {} - /// 超时,未执行完将自动提交 - void Transaction(Action handler, TimeSpan timeout); - /// - /// 当前线程的事务 - /// - DbTransaction TransactionCurrentThread { get; } - #endregion + #region 事务 + /// + /// 开启事务(不支持异步),60秒未执行完将自动提交 + /// + /// 事务体 () => {} + void Transaction(Action handler); + /// + /// 开启事务(不支持异步) + /// + /// 事务体 () => {} + /// 超时,未执行完将自动提交 + void Transaction(Action handler, TimeSpan timeout); + /// + /// 当前线程的事务 + /// + DbTransaction TransactionCurrentThread { get; } + #endregion - /// - /// 查询,若使用读写分离,查询【从库】条件cmdText.StartsWith("SELECT "),否则查询【主库】 - /// - /// - /// - /// - /// - void ExecuteReader(Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - void ExecuteReader(DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - void ExecuteReader(DbConnection connection, DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 查询,ExecuteReader(dr => {}, "select * from user where age > @age", new { age = 25 }) - /// - /// - /// - void ExecuteReader(Action readerHander, string cmdText, object parms = null); - void ExecuteReader(DbTransaction transaction, Action readerHander, string cmdText, object parms = null); - void ExecuteReader(DbConnection connection, DbTransaction transaction, Action readerHander, string cmdText, object parms = null); - /// - /// 查询 - /// - /// - /// - object[][] ExecuteArray(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - object[][] ExecuteArray(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - object[][] ExecuteArray(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 查询,ExecuteArray("select * from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - object[][] ExecuteArray(string cmdText, object parms = null); - object[][] ExecuteArray(DbTransaction transaction, string cmdText, object parms = null); - object[][] ExecuteArray(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 查询 - /// - /// - /// - DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - DataSet ExecuteDataSet(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - DataSet ExecuteDataSet(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 查询,ExecuteDataSet("select * from user where age > @age; select 2", new { age = 25 }) - /// - /// - /// - /// - DataSet ExecuteDataSet(string cmdText, object parms = null); - DataSet ExecuteDataSet(DbTransaction transaction, string cmdText, object parms = null); - DataSet ExecuteDataSet(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 查询 - /// - /// - /// - DataTable ExecuteDataTable(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - DataTable ExecuteDataTable(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - DataTable ExecuteDataTable(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 查询,ExecuteDataTable("select * from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - DataTable ExecuteDataTable(string cmdText, object parms = null); - DataTable ExecuteDataTable(DbTransaction transaction, string cmdText, object parms = null); - DataTable ExecuteDataTable(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 在【主库】执行 - /// - /// - /// - /// - int ExecuteNonQuery(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - int ExecuteNonQuery(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - int ExecuteNonQuery(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 在【主库】执行,ExecuteNonQuery("delete from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - int ExecuteNonQuery(string cmdText, object parms = null); - int ExecuteNonQuery(DbTransaction transaction, string cmdText, object parms = null); - int ExecuteNonQuery(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 在【主库】执行 - /// - /// - /// - /// - object ExecuteScalar(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - object ExecuteScalar(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - object ExecuteScalar(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 在【主库】执行,ExecuteScalar("select 1 from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - object ExecuteScalar(string cmdText, object parms = null); - object ExecuteScalar(DbTransaction transaction, string cmdText, object parms = null); - object ExecuteScalar(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 查询,若使用读写分离,查询【从库】条件cmdText.StartsWith("SELECT "),否则查询【主库】 + /// + /// + /// + /// + /// + void ExecuteReader(Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + void ExecuteReader(DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + void ExecuteReader(DbConnection connection, DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 查询,ExecuteReader(dr => {}, "select * from user where age > @age", new { age = 25 }) + /// + /// + /// + void ExecuteReader(Action readerHander, string cmdText, object parms = null); + void ExecuteReader(DbTransaction transaction, Action readerHander, string cmdText, object parms = null); + void ExecuteReader(DbConnection connection, DbTransaction transaction, Action readerHander, string cmdText, object parms = null); + /// + /// 查询 + /// + /// + /// + object[][] ExecuteArray(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + object[][] ExecuteArray(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + object[][] ExecuteArray(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 查询,ExecuteArray("select * from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + object[][] ExecuteArray(string cmdText, object parms = null); + object[][] ExecuteArray(DbTransaction transaction, string cmdText, object parms = null); + object[][] ExecuteArray(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 查询 + /// + /// + /// + DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + DataSet ExecuteDataSet(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + DataSet ExecuteDataSet(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 查询,ExecuteDataSet("select * from user where age > @age; select 2", new { age = 25 }) + /// + /// + /// + /// + DataSet ExecuteDataSet(string cmdText, object parms = null); + DataSet ExecuteDataSet(DbTransaction transaction, string cmdText, object parms = null); + DataSet ExecuteDataSet(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 查询 + /// + /// + /// + DataTable ExecuteDataTable(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + DataTable ExecuteDataTable(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + DataTable ExecuteDataTable(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 查询,ExecuteDataTable("select * from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + DataTable ExecuteDataTable(string cmdText, object parms = null); + DataTable ExecuteDataTable(DbTransaction transaction, string cmdText, object parms = null); + DataTable ExecuteDataTable(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 在【主库】执行 + /// + /// + /// + /// + int ExecuteNonQuery(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + int ExecuteNonQuery(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + int ExecuteNonQuery(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 在【主库】执行,ExecuteNonQuery("delete from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + int ExecuteNonQuery(string cmdText, object parms = null); + int ExecuteNonQuery(DbTransaction transaction, string cmdText, object parms = null); + int ExecuteNonQuery(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 在【主库】执行 + /// + /// + /// + /// + object ExecuteScalar(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + object ExecuteScalar(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + object ExecuteScalar(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 在【主库】执行,ExecuteScalar("select 1 from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + object ExecuteScalar(string cmdText, object parms = null); + object ExecuteScalar(DbTransaction transaction, string cmdText, object parms = null); + object ExecuteScalar(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age", new SqlParameter { ParameterName = "age", Value = 25 }) - /// - /// - /// - /// - /// - /// - List Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - List Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - List Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - /// - List Query(string cmdText, object parms = null); - List Query(DbTransaction transaction, string cmdText, object parms = null); - List Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age", new SqlParameter { ParameterName = "age", Value = 25 }) + /// + /// + /// + /// + /// + /// + List Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + List Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + List Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + /// + List Query(string cmdText, object parms = null); + List Query(DbTransaction transaction, string cmdText, object parms = null); + List Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age; select * from address", new SqlParameter { ParameterName = "age", Value = 25 }) - /// - /// - /// - /// - /// - /// - (List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age; select * from address", new { age = 25 }) - /// - /// - /// - /// - /// - (List, List) Query(string cmdText, object parms = null); - (List, List) Query(DbTransaction transaction, string cmdText, object parms = null); - (List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age; select * from address", new SqlParameter { ParameterName = "age", Value = 25 }) + /// + /// + /// + /// + /// + /// + (List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age; select * from address", new { age = 25 }) + /// + /// + /// + /// + /// + (List, List) Query(string cmdText, object parms = null); + (List, List) Query(DbTransaction transaction, string cmdText, object parms = null); + (List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - (List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List) Query(string cmdText, object parms = null); - (List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null); - (List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - (List, List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List, List) Query(string cmdText, object parms = null); - (List, List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null); - (List, List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - (List, List, List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - (List, List, List, List, List) Query(string cmdText, object parms = null); - (List, List, List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null); - (List, List, List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + (List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List) Query(string cmdText, object parms = null); + (List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null); + (List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + (List, List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List, List) Query(string cmdText, object parms = null); + (List, List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null); + (List, List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + (List, List, List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + (List, List, List, List, List) Query(string cmdText, object parms = null); + (List, List, List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null); + (List, List, List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - #region async - /// - /// 查询,若使用读写分离,查询【从库】条件cmdText.StartsWith("SELECT "),否则查询【主库】 - /// - /// - /// - /// - /// - Task ExecuteReaderAsync(Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteReaderAsync(DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 查询,ExecuteReaderAsync(dr => {}, "select * from user where age > @age", new { age = 25 }) - /// - /// - /// - Task ExecuteReaderAsync(Func readerHander, string cmdText, object parms = null); - Task ExecuteReaderAsync(DbTransaction transaction, Func readerHander, string cmdText, object parms = null); - Task ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, Func readerHander, string cmdText, object parms = null); - /// - /// 查询 - /// - /// - /// - Task ExecuteArrayAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteArrayAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteArrayAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 查询,ExecuteArrayAsync("select * from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - Task ExecuteArrayAsync(string cmdText, object parms = null); - Task ExecuteArrayAsync(DbTransaction transaction, string cmdText, object parms = null); - Task ExecuteArrayAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 查询 - /// - /// - /// - Task ExecuteDataSetAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteDataSetAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteDataSetAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 查询,ExecuteDataSetAsync("select * from user where age > @age; select 2", new { age = 25 }) - /// - /// - /// - /// - Task ExecuteDataSetAsync(string cmdText, object parms = null); - Task ExecuteDataSetAsync(DbTransaction transaction, string cmdText, object parms = null); - Task ExecuteDataSetAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 查询 - /// - /// - /// - Task ExecuteDataTableAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteDataTableAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteDataTableAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 查询,ExecuteDataTableAsync("select * from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - Task ExecuteDataTableAsync(string cmdText, object parms = null); - Task ExecuteDataTableAsync(DbTransaction transaction, string cmdText, object parms = null); - Task ExecuteDataTableAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 在【主库】执行 - /// - /// - /// - /// - Task ExecuteNonQueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteNonQueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteNonQueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 在【主库】执行,ExecuteNonQueryAsync("delete from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - Task ExecuteNonQueryAsync(string cmdText, object parms = null); - Task ExecuteNonQueryAsync(DbTransaction transaction, string cmdText, object parms = null); - Task ExecuteNonQueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 在【主库】执行 - /// - /// - /// - /// - Task ExecuteScalarAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteScalarAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 在【主库】执行,ExecuteScalarAsync("select 1 from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - Task ExecuteScalarAsync(string cmdText, object parms = null); - Task ExecuteScalarAsync(DbTransaction transaction, string cmdText, object parms = null); - Task ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + #region async + /// + /// 查询,若使用读写分离,查询【从库】条件cmdText.StartsWith("SELECT "),否则查询【主库】 + /// + /// + /// + /// + /// + Task ExecuteReaderAsync(Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteReaderAsync(DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 查询,ExecuteReaderAsync(dr => {}, "select * from user where age > @age", new { age = 25 }) + /// + /// + /// + Task ExecuteReaderAsync(Func readerHander, string cmdText, object parms = null); + Task ExecuteReaderAsync(DbTransaction transaction, Func readerHander, string cmdText, object parms = null); + Task ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, Func readerHander, string cmdText, object parms = null); + /// + /// 查询 + /// + /// + /// + Task ExecuteArrayAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteArrayAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteArrayAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 查询,ExecuteArrayAsync("select * from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + Task ExecuteArrayAsync(string cmdText, object parms = null); + Task ExecuteArrayAsync(DbTransaction transaction, string cmdText, object parms = null); + Task ExecuteArrayAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 查询 + /// + /// + /// + Task ExecuteDataSetAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteDataSetAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteDataSetAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 查询,ExecuteDataSetAsync("select * from user where age > @age; select 2", new { age = 25 }) + /// + /// + /// + /// + Task ExecuteDataSetAsync(string cmdText, object parms = null); + Task ExecuteDataSetAsync(DbTransaction transaction, string cmdText, object parms = null); + Task ExecuteDataSetAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 查询 + /// + /// + /// + Task ExecuteDataTableAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteDataTableAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteDataTableAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 查询,ExecuteDataTableAsync("select * from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + Task ExecuteDataTableAsync(string cmdText, object parms = null); + Task ExecuteDataTableAsync(DbTransaction transaction, string cmdText, object parms = null); + Task ExecuteDataTableAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 在【主库】执行 + /// + /// + /// + /// + Task ExecuteNonQueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteNonQueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteNonQueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 在【主库】执行,ExecuteNonQueryAsync("delete from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + Task ExecuteNonQueryAsync(string cmdText, object parms = null); + Task ExecuteNonQueryAsync(DbTransaction transaction, string cmdText, object parms = null); + Task ExecuteNonQueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 在【主库】执行 + /// + /// + /// + /// + Task ExecuteScalarAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteScalarAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 在【主库】执行,ExecuteScalarAsync("select 1 from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + Task ExecuteScalarAsync(string cmdText, object parms = null); + Task ExecuteScalarAsync(DbTransaction transaction, string cmdText, object parms = null); + Task ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 执行SQL返回对象集合,QueryAsync<User>("select * from user where age > @age", new SqlParameter { ParameterName = "age", Value = 25 }) - /// - /// - /// - /// - /// - /// - Task> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 执行SQL返回对象集合,QueryAsync<User>("select * from user where age > @age", new { age = 25 }) - /// - /// - /// - /// - /// - Task> QueryAsync(string cmdText, object parms = null); - Task> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); - Task> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 执行SQL返回对象集合,QueryAsync<User>("select * from user where age > @age", new SqlParameter { ParameterName = "age", Value = 25 }) + /// + /// + /// + /// + /// + /// + Task> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 执行SQL返回对象集合,QueryAsync<User>("select * from user where age > @age", new { age = 25 }) + /// + /// + /// + /// + /// + Task> QueryAsync(string cmdText, object parms = null); + Task> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); + Task> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - /// - /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age; select * from address", new SqlParameter { ParameterName = "age", Value = 25 }) - /// - /// - /// - /// - /// - /// - Task<(List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - /// - /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age; select * from address", new { age = 25 }) - /// - /// - /// - /// - /// - Task<(List, List)> QueryAsync(string cmdText, object parms = null); - Task<(List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); - Task<(List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + /// + /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age; select * from address", new SqlParameter { ParameterName = "age", Value = 25 }) + /// + /// + /// + /// + /// + /// + Task<(List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + /// + /// 执行SQL返回对象集合,Query<User>("select * from user where age > @age; select * from address", new { age = 25 }) + /// + /// + /// + /// + /// + Task<(List, List)> QueryAsync(string cmdText, object parms = null); + Task<(List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); + Task<(List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - Task<(List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List)> QueryAsync(string cmdText, object parms = null); - Task<(List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); - Task<(List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - Task<(List, List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List, List)> QueryAsync(string cmdText, object parms = null); - Task<(List, List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); - Task<(List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - Task<(List, List, List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); - Task<(List, List, List, List, List)> QueryAsync(string cmdText, object parms = null); - Task<(List, List, List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); - Task<(List, List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); - #endregion - } + Task<(List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List)> QueryAsync(string cmdText, object parms = null); + Task<(List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); + Task<(List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + Task<(List, List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List, List)> QueryAsync(string cmdText, object parms = null); + Task<(List, List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); + Task<(List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + Task<(List, List, List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms); + Task<(List, List, List, List, List)> QueryAsync(string cmdText, object parms = null); + Task<(List, List, List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null); + Task<(List, List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null); + #endregion + } } diff --git a/FreeSql/Interface/IAop.cs b/FreeSql/Interface/IAop.cs index 6fb82996..4b777b2f 100644 --- a/FreeSql/Interface/IAop.cs +++ b/FreeSql/Interface/IAop.cs @@ -7,238 +7,261 @@ using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; -namespace FreeSql { - public interface IAop { +namespace FreeSql +{ + public interface IAop + { - /// - /// 监控 ToList 返回的的数据,用于拦截重新装饰 - /// - EventHandler ToList { get; set; } + /// + /// 监控 ToList 返回的的数据,用于拦截重新装饰 + /// + EventHandler ToList { get; set; } - /// - /// 监视 Where,包括 select/update/delete,可控制使上层不被执行。 - /// - EventHandler Where { get; set; } + /// + /// 监视 Where,包括 select/update/delete,可控制使上层不被执行。 + /// + EventHandler Where { get; set; } - /// - /// 可自定义解析表达式 - /// - EventHandler ParseExpression { get; set; } + /// + /// 可自定义解析表达式 + /// + EventHandler ParseExpression { get; set; } - /// - /// 自定义实体的配置,方便和多个 ORM 共同使用 - /// - EventHandler ConfigEntity { get; set; } - /// - /// 自定义实体的属性配置,方便和多个 ORM 共同使用 - /// - EventHandler ConfigEntityProperty { get; set; } + /// + /// 自定义实体的配置,方便和多个 ORM 共同使用 + /// + EventHandler ConfigEntity { get; set; } + /// + /// 自定义实体的属性配置,方便和多个 ORM 共同使用 + /// + EventHandler ConfigEntityProperty { get; set; } - /// - /// 增删查改,执行命令之前触发 - /// - EventHandler CurdBefore { get; set; } - /// - /// 增删查改,执行命令完成后触发 - /// - EventHandler CurdAfter { get; set; } + /// + /// 增删查改,执行命令之前触发 + /// + EventHandler CurdBefore { get; set; } + /// + /// 增删查改,执行命令完成后触发 + /// + EventHandler CurdAfter { get; set; } - /// - /// CodeFirst迁移,执行之前触发 - /// - EventHandler SyncStructureBefore { get; set; } - /// - /// CodeFirst迁移,执行完成触发 - /// - EventHandler SyncStructureAfter { get; set; } - } + /// + /// CodeFirst迁移,执行之前触发 + /// + EventHandler SyncStructureBefore { get; set; } + /// + /// CodeFirst迁移,执行完成触发 + /// + EventHandler SyncStructureAfter { get; set; } + } } -namespace FreeSql.Aop { - public class ToListEventArgs : EventArgs { - public ToListEventArgs(object list) { - this.List = list; - } - /// - /// 可重新装饰的引用数据 - /// - public object List { get; } - } - public class WhereEventArgs : EventArgs { - public WhereEventArgs(params object[] parameters) { - this.Parameters = parameters; - } - public object[] Parameters { get; } - /// - /// 可使上层不被执行这个条件 - /// - public bool IsCancel { get; set; } - } - public class ParseExpressionEventArgs : EventArgs { - public ParseExpressionEventArgs(Expression expression, Func freeParse) { - this.Expression = expression; - this.FreeParse = freeParse; - } +namespace FreeSql.Aop +{ + public class ToListEventArgs : EventArgs + { + public ToListEventArgs(object list) + { + this.List = list; + } + /// + /// 可重新装饰的引用数据 + /// + public object List { get; } + } + public class WhereEventArgs : EventArgs + { + public WhereEventArgs(params object[] parameters) + { + this.Parameters = parameters; + } + public object[] Parameters { get; } + /// + /// 可使上层不被执行这个条件 + /// + public bool IsCancel { get; set; } + } + public class ParseExpressionEventArgs : EventArgs + { + public ParseExpressionEventArgs(Expression expression, Func freeParse) + { + this.Expression = expression; + this.FreeParse = freeParse; + } - /// - /// 内置解析功能,可辅助您进行解析 - /// - public Func FreeParse { get; } + /// + /// 内置解析功能,可辅助您进行解析 + /// + public Func FreeParse { get; } - /// - /// 需要您解析的表达式 - /// - public Expression Expression { get; } - /// - /// 解析后的内容 - /// - public string Result { get; set; } - } - public class ConfigEntityEventArgs : EventArgs { - public ConfigEntityEventArgs(Type entityType) { - this.EntityType = entityType; - this.ModifyResult = new TableAttribute(); - } + /// + /// 需要您解析的表达式 + /// + public Expression Expression { get; } + /// + /// 解析后的内容 + /// + public string Result { get; set; } + } + public class ConfigEntityEventArgs : EventArgs + { + public ConfigEntityEventArgs(Type entityType) + { + this.EntityType = entityType; + this.ModifyResult = new TableAttribute(); + } - /// - /// 实体类型 - /// - public Type EntityType { get; } - /// - /// 实体配置 - /// - public TableAttribute ModifyResult { get; } - } - public class ConfigEntityPropertyEventArgs : EventArgs { - public ConfigEntityPropertyEventArgs(Type entityType, PropertyInfo property) { - this.EntityType = entityType; - this.Property = property; - this.ModifyResult = new ColumnAttribute(); - } + /// + /// 实体类型 + /// + public Type EntityType { get; } + /// + /// 实体配置 + /// + public TableAttribute ModifyResult { get; } + } + public class ConfigEntityPropertyEventArgs : EventArgs + { + public ConfigEntityPropertyEventArgs(Type entityType, PropertyInfo property) + { + this.EntityType = entityType; + this.Property = property; + this.ModifyResult = new ColumnAttribute(); + } - /// - /// 实体类型 - /// - public Type EntityType { get; } - /// - /// 实体的属性 - /// - public PropertyInfo Property { get; } - /// - /// 实体的属性配置 - /// - public ColumnAttribute ModifyResult { get; } - } + /// + /// 实体类型 + /// + public Type EntityType { get; } + /// + /// 实体的属性 + /// + public PropertyInfo Property { get; } + /// + /// 实体的属性配置 + /// + public ColumnAttribute ModifyResult { get; } + } - public class CurdBeforeEventArgs : EventArgs { - public CurdBeforeEventArgs(Type entityType, CurdType curdType, string sql, DbParameter[] dbParms) : - this(Guid.NewGuid(), new Stopwatch(), entityType, curdType, sql, dbParms) { - this.Stopwatch.Start(); - } - protected CurdBeforeEventArgs(Guid identifier, Stopwatch stopwatch, Type entityType, CurdType curdType, string sql, DbParameter[] dbParms) { - this.Identifier = identifier; - this.Stopwatch = stopwatch; - this.EntityType = entityType; - this.CurdType = curdType; - this.Sql = sql; - this.DbParms = dbParms; - } + public class CurdBeforeEventArgs : EventArgs + { + public CurdBeforeEventArgs(Type entityType, CurdType curdType, string sql, DbParameter[] dbParms) : + this(Guid.NewGuid(), new Stopwatch(), entityType, curdType, sql, dbParms) + { + this.Stopwatch.Start(); + } + protected CurdBeforeEventArgs(Guid identifier, Stopwatch stopwatch, Type entityType, CurdType curdType, string sql, DbParameter[] dbParms) + { + this.Identifier = identifier; + this.Stopwatch = stopwatch; + this.EntityType = entityType; + this.CurdType = curdType; + this.Sql = sql; + this.DbParms = dbParms; + } - /// - /// 标识符,可将 CurdBefore 与 CurdAfter 进行匹配 - /// - public Guid Identifier { get; protected set; } - protected Stopwatch Stopwatch { get; } - internal Stopwatch StopwatchInternal => Stopwatch; - /// - /// 操作类型 - /// - public CurdType CurdType { get; } - /// - /// 实体类型 - /// - public Type EntityType { get; } - /// - /// 执行的 SQL - /// - public string Sql { get; } - /// - /// 参数化命令 - /// - public DbParameter[] DbParms { get; } - } - public enum CurdType { Select, Delete, Update, Insert } - public class CurdAfterEventArgs : CurdBeforeEventArgs { - public CurdAfterEventArgs(CurdBeforeEventArgs before, Exception exception, object executeResult) : - base(before.Identifier, before.StopwatchInternal, before.EntityType, before.CurdType, before.Sql, before.DbParms) { - this.Exception = exception; - this.ExecuteResult = executeResult; - this.Stopwatch.Stop(); - } + /// + /// 标识符,可将 CurdBefore 与 CurdAfter 进行匹配 + /// + public Guid Identifier { get; protected set; } + protected Stopwatch Stopwatch { get; } + internal Stopwatch StopwatchInternal => Stopwatch; + /// + /// 操作类型 + /// + public CurdType CurdType { get; } + /// + /// 实体类型 + /// + public Type EntityType { get; } + /// + /// 执行的 SQL + /// + public string Sql { get; } + /// + /// 参数化命令 + /// + public DbParameter[] DbParms { get; } + } + public enum CurdType { Select, Delete, Update, Insert } + public class CurdAfterEventArgs : CurdBeforeEventArgs + { + public CurdAfterEventArgs(CurdBeforeEventArgs before, Exception exception, object executeResult) : + base(before.Identifier, before.StopwatchInternal, before.EntityType, before.CurdType, before.Sql, before.DbParms) + { + this.Exception = exception; + this.ExecuteResult = executeResult; + this.Stopwatch.Stop(); + } - /// - /// 发生的错误 - /// - public Exception Exception { get; } - /// - /// 执行SQL命令,返回的结果 - /// - public object ExecuteResult { get; set; } - /// - /// 耗时(单位:Ticks) - /// - public long ElapsedTicks => this.Stopwatch.ElapsedTicks; - /// - /// 耗时(单位:毫秒) - /// - public long ElapsedMilliseconds => this.Stopwatch.ElapsedMilliseconds; - } + /// + /// 发生的错误 + /// + public Exception Exception { get; } + /// + /// 执行SQL命令,返回的结果 + /// + public object ExecuteResult { get; set; } + /// + /// 耗时(单位:Ticks) + /// + public long ElapsedTicks => this.Stopwatch.ElapsedTicks; + /// + /// 耗时(单位:毫秒) + /// + public long ElapsedMilliseconds => this.Stopwatch.ElapsedMilliseconds; + } - public class SyncStructureBeforeEventArgs : EventArgs { - public SyncStructureBeforeEventArgs(Type[] entityTypes) : - this(Guid.NewGuid(), new Stopwatch(), entityTypes) { - this.Stopwatch.Start(); - } - protected SyncStructureBeforeEventArgs(Guid identifier, Stopwatch stopwatch, Type[] entityTypes) { - this.Identifier = identifier; - this.Stopwatch = stopwatch; - this.EntityTypes = entityTypes; - } + public class SyncStructureBeforeEventArgs : EventArgs + { + public SyncStructureBeforeEventArgs(Type[] entityTypes) : + this(Guid.NewGuid(), new Stopwatch(), entityTypes) + { + this.Stopwatch.Start(); + } + protected SyncStructureBeforeEventArgs(Guid identifier, Stopwatch stopwatch, Type[] entityTypes) + { + this.Identifier = identifier; + this.Stopwatch = stopwatch; + this.EntityTypes = entityTypes; + } - /// - /// 标识符,可将 SyncStructureBeforeEventArgs 与 SyncStructureAfterEventArgs 进行匹配 - /// - public Guid Identifier { get; protected set; } - protected Stopwatch Stopwatch { get; } - internal Stopwatch StopwatchInternal => Stopwatch; - /// - /// 实体类型 - /// - public Type[] EntityTypes { get; } - } - public class SyncStructureAfterEventArgs : SyncStructureBeforeEventArgs { - public SyncStructureAfterEventArgs(SyncStructureBeforeEventArgs before, string sql, Exception exception) : - base(before.Identifier, before.StopwatchInternal, before.EntityTypes) { - this.Sql = sql; - this.Exception = exception; - this.Stopwatch.Stop(); - } + /// + /// 标识符,可将 SyncStructureBeforeEventArgs 与 SyncStructureAfterEventArgs 进行匹配 + /// + public Guid Identifier { get; protected set; } + protected Stopwatch Stopwatch { get; } + internal Stopwatch StopwatchInternal => Stopwatch; + /// + /// 实体类型 + /// + public Type[] EntityTypes { get; } + } + public class SyncStructureAfterEventArgs : SyncStructureBeforeEventArgs + { + public SyncStructureAfterEventArgs(SyncStructureBeforeEventArgs before, string sql, Exception exception) : + base(before.Identifier, before.StopwatchInternal, before.EntityTypes) + { + this.Sql = sql; + this.Exception = exception; + this.Stopwatch.Stop(); + } - /// - /// 执行的 SQL - /// - public string Sql { get; } - /// - /// 发生的错误 - /// - public Exception Exception { get; } - /// - /// 耗时(单位:Ticks) - /// - public long ElapsedTicks => this.Stopwatch.ElapsedTicks; - /// - /// 耗时(单位:毫秒) - /// - public long ElapsedMilliseconds => this.Stopwatch.ElapsedMilliseconds; - } + /// + /// 执行的 SQL + /// + public string Sql { get; } + /// + /// 发生的错误 + /// + public Exception Exception { get; } + /// + /// 耗时(单位:Ticks) + /// + public long ElapsedTicks => this.Stopwatch.ElapsedTicks; + /// + /// 耗时(单位:毫秒) + /// + public long ElapsedMilliseconds => this.Stopwatch.ElapsedMilliseconds; + } } \ No newline at end of file diff --git a/FreeSql/Interface/ICodeFirst.cs b/FreeSql/Interface/ICodeFirst.cs index 5e0c06dd..de49488a 100644 --- a/FreeSql/Interface/ICodeFirst.cs +++ b/FreeSql/Interface/ICodeFirst.cs @@ -2,91 +2,93 @@ using FreeSql.Internal.Model; using System; -namespace FreeSql { - public interface ICodeFirst { +namespace FreeSql +{ + public interface ICodeFirst + { - /// - /// 【开发环境必备】自动同步实体结构到数据库,程序运行中检查实体表是否存在,然后创建或修改 - /// - bool IsAutoSyncStructure { get; set; } + /// + /// 【开发环境必备】自动同步实体结构到数据库,程序运行中检查实体表是否存在,然后创建或修改 + /// + bool IsAutoSyncStructure { get; set; } - /// - /// 转小写同步结构 - /// - bool IsSyncStructureToLower { get; set; } - /// - /// 转大写同步结构 - /// - bool IsSyncStructureToUpper { get; set; } - /// - /// 使用数据库的主键和自增,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql。 - /// - bool IsConfigEntityFromDbFirst { get; set; } - /// - /// 不使用命令参数化执行,针对 Insert/Update - /// - bool IsNoneCommandParameter { get; set; } - /// - /// 延时加载导航属性对象,导航属性需要声明 virtual - /// - bool IsLazyLoading { get; set; } + /// + /// 转小写同步结构 + /// + bool IsSyncStructureToLower { get; set; } + /// + /// 转大写同步结构 + /// + bool IsSyncStructureToUpper { get; set; } + /// + /// 使用数据库的主键和自增,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql。 + /// + bool IsConfigEntityFromDbFirst { get; set; } + /// + /// 不使用命令参数化执行,针对 Insert/Update + /// + bool IsNoneCommandParameter { get; set; } + /// + /// 延时加载导航属性对象,导航属性需要声明 virtual + /// + bool IsLazyLoading { get; set; } - /// - /// 将实体类型与数据库对比,返回DDL语句 - /// - /// - /// - string GetComparisonDDLStatements(); - /// - /// 将实体类型集合与数据库对比,返回DDL语句 - /// - /// - /// - string GetComparisonDDLStatements(params Type[] entityTypes); - /// - /// 同步实体类型到数据库 - /// - /// - /// - bool SyncStructure(); - /// - /// 同步实体类型集合到数据库 - /// - /// - /// - bool SyncStructure(params Type[] entityTypes); + /// + /// 将实体类型与数据库对比,返回DDL语句 + /// + /// + /// + string GetComparisonDDLStatements(); + /// + /// 将实体类型集合与数据库对比,返回DDL语句 + /// + /// + /// + string GetComparisonDDLStatements(params Type[] entityTypes); + /// + /// 同步实体类型到数据库 + /// + /// + /// + bool SyncStructure(); + /// + /// 同步实体类型集合到数据库 + /// + /// + /// + bool SyncStructure(params Type[] entityTypes); - /// - /// 根据 System.Type 获取数据库信息 - /// - /// - /// - (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type); - /// - /// 在外部配置实体的特性 - /// - /// - /// - /// - ICodeFirst ConfigEntity(Action> entity); - /// - /// 在外部配置实体的特性 - /// - /// - /// - /// - ICodeFirst ConfigEntity(Type type, Action entity); - /// - /// 获取在外部配置实体的特性 - /// - /// - /// 未使用ConfigEntity配置时,返回null - TableAttribute GetConfigEntity(Type type); - /// - /// 获取实体类核心配置 - /// - /// - /// - TableInfo GetTableByEntity(Type type); - } + /// + /// 根据 System.Type 获取数据库信息 + /// + /// + /// + (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type); + /// + /// 在外部配置实体的特性 + /// + /// + /// + /// + ICodeFirst ConfigEntity(Action> entity); + /// + /// 在外部配置实体的特性 + /// + /// + /// + /// + ICodeFirst ConfigEntity(Type type, Action entity); + /// + /// 获取在外部配置实体的特性 + /// + /// + /// 未使用ConfigEntity配置时,返回null + TableAttribute GetConfigEntity(Type type); + /// + /// 获取实体类核心配置 + /// + /// + /// + TableInfo GetTableByEntity(Type type); + } } diff --git a/FreeSql/Interface/IFreeSql.cs b/FreeSql/Interface/IFreeSql.cs index 5b489424..bf5c9260 100644 --- a/FreeSql/Interface/IFreeSql.cs +++ b/FreeSql/Interface/IFreeSql.cs @@ -4,104 +4,105 @@ using System.Collections.Generic; public interface IFreeSql : IFreeSql { } -public interface IFreeSql : IDisposable { - /// - /// 插入数据 - /// - /// - /// - IInsert Insert() where T1 : class; - /// - /// 插入数据,传入实体 - /// - /// - /// - /// - IInsert Insert(T1 source) where T1 : class; - /// - /// 插入数据,传入实体数组 - /// - /// - /// - /// - IInsert Insert(T1[] source) where T1 : class; - /// - /// 插入数据,传入实体集合 - /// - /// - /// - /// - IInsert Insert(IEnumerable source) where T1 : class; +public interface IFreeSql : IDisposable +{ + /// + /// 插入数据 + /// + /// + /// + IInsert Insert() where T1 : class; + /// + /// 插入数据,传入实体 + /// + /// + /// + /// + IInsert Insert(T1 source) where T1 : class; + /// + /// 插入数据,传入实体数组 + /// + /// + /// + /// + IInsert Insert(T1[] source) where T1 : class; + /// + /// 插入数据,传入实体集合 + /// + /// + /// + /// + IInsert Insert(IEnumerable source) where T1 : class; - /// - /// 修改数据 - /// - /// - /// - IUpdate Update() where T1 : class; - /// - /// 修改数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} - /// - /// - /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 - /// - IUpdate Update(object dywhere) where T1 : class; + /// + /// 修改数据 + /// + /// + /// + IUpdate Update() where T1 : class; + /// + /// 修改数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} + /// + /// + /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 + /// + IUpdate Update(object dywhere) where T1 : class; - /// - /// 查询数据 - /// - /// - /// - ISelect Select() where T1 : class; - /// - /// 查询数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} - /// - /// - /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 - /// - ISelect Select(object dywhere) where T1 : class; + /// + /// 查询数据 + /// + /// + /// + ISelect Select() where T1 : class; + /// + /// 查询数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} + /// + /// + /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 + /// + ISelect Select(object dywhere) where T1 : class; - /// - /// 删除数据 - /// - /// - /// - IDelete Delete() where T1 : class; - /// - /// 删除数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} - /// - /// - /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 - /// - IDelete Delete(object dywhere) where T1 : class; + /// + /// 删除数据 + /// + /// + /// + IDelete Delete() where T1 : class; + /// + /// 删除数据,传入动态对象如:主键值 | new[]{主键值1,主键值2} | TEntity1 | new[]{TEntity1,TEntity2} | new{id=1} + /// + /// + /// 主键值、主键值集合、实体、实体集合、匿名对象、匿名对象集合 + /// + IDelete Delete(object dywhere) where T1 : class; - /// - /// 开启事务(不支持异步),60秒未执行完将自动提交 - /// - /// 事务体 () => {} - void Transaction(Action handler); - /// - /// 开启事务(不支持异步) - /// - /// 事务体 () => {} - /// 超时,未执行完将自动提交 - void Transaction(Action handler, TimeSpan timeout); + /// + /// 开启事务(不支持异步),60秒未执行完将自动提交 + /// + /// 事务体 () => {} + void Transaction(Action handler); + /// + /// 开启事务(不支持异步) + /// + /// 事务体 () => {} + /// 超时,未执行完将自动提交 + void Transaction(Action handler, TimeSpan timeout); - /// - /// 数据库访问对象 - /// - IAdo Ado { get; } - /// - /// 所有拦截方法都在这里 - /// - IAop Aop { get; } + /// + /// 数据库访问对象 + /// + IAdo Ado { get; } + /// + /// 所有拦截方法都在这里 + /// + IAop Aop { get; } - /// - /// CodeFirst 模式开发相关方法 - /// - ICodeFirst CodeFirst { get; } - /// - /// DbFirst 模式开发相关方法 - /// - IDbFirst DbFirst { get; } + /// + /// CodeFirst 模式开发相关方法 + /// + ICodeFirst CodeFirst { get; } + /// + /// DbFirst 模式开发相关方法 + /// + IDbFirst DbFirst { get; } } \ No newline at end of file diff --git a/FreeSql/Interface/iDbFirst.cs b/FreeSql/Interface/iDbFirst.cs index 2aa495a8..1c444593 100644 --- a/FreeSql/Interface/iDbFirst.cs +++ b/FreeSql/Interface/iDbFirst.cs @@ -2,76 +2,78 @@ using System; using System.Collections.Generic; -namespace FreeSql { - public interface IDbFirst { +namespace FreeSql +{ + public interface IDbFirst + { - /// - /// 获取所有数据库 - /// - /// - List GetDatabases(); - /// - /// 获取指定数据库的表信息,包括表、列详情、主键、唯一键、索引、外键、备注 - /// - /// - /// - List GetTablesByDatabase(params string[] database); + /// + /// 获取所有数据库 + /// + /// + List GetDatabases(); + /// + /// 获取指定数据库的表信息,包括表、列详情、主键、唯一键、索引、外键、备注 + /// + /// + /// + List GetTablesByDatabase(params string[] database); - /// - /// 获取数据库枚举类型int值 - /// - /// - /// - int GetDbType(DbColumnInfo column); + /// + /// 获取数据库枚举类型int值 + /// + /// + /// + int GetDbType(DbColumnInfo column); - /// - /// 获取c#转换,(int)、(long) - /// - /// - /// - string GetCsConvert(DbColumnInfo column); - /// - /// 获取c#值 - /// - /// - /// - string GetCsTypeValue(DbColumnInfo column); - /// - /// 获取c#类型,int、long - /// - /// - /// - string GetCsType(DbColumnInfo column); - /// - /// 获取c#类型对象 - /// - /// - /// - Type GetCsTypeInfo(DbColumnInfo column); - /// - /// 获取ado.net读取方法, GetBoolean、GetInt64 - /// - /// - /// - string GetDataReaderMethod(DbColumnInfo column); - /// - /// 序列化 - /// - /// - /// - string GetCsStringify(DbColumnInfo column); - /// - /// 反序列化 - /// - /// - /// - string GetCsParse(DbColumnInfo column); + /// + /// 获取c#转换,(int)、(long) + /// + /// + /// + string GetCsConvert(DbColumnInfo column); + /// + /// 获取c#值 + /// + /// + /// + string GetCsTypeValue(DbColumnInfo column); + /// + /// 获取c#类型,int、long + /// + /// + /// + string GetCsType(DbColumnInfo column); + /// + /// 获取c#类型对象 + /// + /// + /// + Type GetCsTypeInfo(DbColumnInfo column); + /// + /// 获取ado.net读取方法, GetBoolean、GetInt64 + /// + /// + /// + string GetDataReaderMethod(DbColumnInfo column); + /// + /// 序列化 + /// + /// + /// + string GetCsStringify(DbColumnInfo column); + /// + /// 反序列化 + /// + /// + /// + string GetCsParse(DbColumnInfo column); - /// - /// 获取数据库枚举类型,适用 PostgreSQL - /// - /// - /// - List GetEnumsByDatabase(params string[] database); - } + /// + /// 获取数据库枚举类型,适用 PostgreSQL + /// + /// + /// + List GetEnumsByDatabase(params string[] database); + } } diff --git a/FreeSql/Internal/CommonExpression.cs b/FreeSql/Internal/CommonExpression.cs index 740bab69..6f89f5e1 100644 --- a/FreeSql/Internal/CommonExpression.cs +++ b/FreeSql/Internal/CommonExpression.cs @@ -9,962 +9,1113 @@ using System.Linq.Expressions; using System.Reflection; using System.Text; -namespace FreeSql.Internal { - public abstract class CommonExpression { +namespace FreeSql.Internal +{ + public abstract class CommonExpression + { - public CommonUtils _common; - public CommonProvider.AdoProvider _ado => _adoPriv ?? (_adoPriv = _common._orm.Ado as CommonProvider.AdoProvider); - CommonProvider.AdoProvider _adoPriv; - public CommonExpression(CommonUtils common) { - _common = common; - } + public CommonUtils _common; + public CommonProvider.AdoProvider _ado => _adoPriv ?? (_adoPriv = _common._orm.Ado as CommonProvider.AdoProvider); + CommonProvider.AdoProvider _adoPriv; + public CommonExpression(CommonUtils common) + { + _common = common; + } - static ConcurrentDictionary _dicReadAnonymousFieldDtoPropertys = new ConcurrentDictionary(); - public bool ReadAnonymousField(List _tables, StringBuilder field, ReadAnonymousTypeInfo parent, ref int index, Expression exp, Func getSelectGroupingMapString) { - Func getTSC = () => new ExpTSC { _tables = _tables, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where }; - switch (exp.NodeType) { - case ExpressionType.Quote: return ReadAnonymousField(_tables, field, parent, ref index, (exp as UnaryExpression)?.Operand, getSelectGroupingMapString); - case ExpressionType.Lambda: return ReadAnonymousField(_tables, field, parent, ref index, (exp as LambdaExpression)?.Body, getSelectGroupingMapString); - case ExpressionType.Negate: - case ExpressionType.NegateChecked: - parent.DbField = $"-({ExpressionLambdaToSql(exp, getTSC())})"; - field.Append(", ").Append(parent.DbField); - if (index >= 0) field.Append(" as").Append(++index); - return false; - case ExpressionType.Convert: return ReadAnonymousField(_tables, field, parent, ref index, (exp as UnaryExpression)?.Operand, getSelectGroupingMapString); - case ExpressionType.Constant: - var constExp = exp as ConstantExpression; - //处理自定义SQL语句,如: ToList(new { - // ccc = "now()", - // partby = "sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)" - //}),有缺点即 ccc partby 接受类型都是 string,可配合 Convert.ToXxx 类型转换,请看下面的兼容 - parent.DbField = constExp.Type.FullName == "System.String" ? (constExp.Value?.ToString() ?? "NULL") : _common.FormatSql("{0}", constExp?.Value); - field.Append(", ").Append(parent.DbField); - if (index >= 0) field.Append(" as").Append(++index); - return false; - case ExpressionType.Call: - var callExp = exp as MethodCallExpression; - //处理自定义SQL语句,如: ToList(new { - // ccc = Convert.ToDateTime("now()"), - // partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") - //}) - if (callExp.Method?.DeclaringType.FullName == "System.Convert" && - callExp.Method.Name.StartsWith("To") && - callExp.Arguments[0].NodeType == ExpressionType.Constant && - callExp.Arguments[0].Type.FullName == "System.String") - parent.DbField = (callExp.Arguments[0] as ConstantExpression).Value?.ToString() ?? "NULL"; - else - parent.DbField = ExpressionLambdaToSql(exp, getTSC()); - field.Append(", ").Append(parent.DbField); - if (index >= 0) field.Append(" as").Append(++index); - return false; - case ExpressionType.Parameter: - case ExpressionType.MemberAccess: - if (_common.GetTableByEntity(exp.Type) != null) { //加载表所有字段 - var map = new List(); - ExpressionSelectColumn_MemberAccess(_tables, map, SelectTableInfoType.From, exp, true, getSelectGroupingMapString); - var tb = parent.Table = map.First().Table.Table; - parent.Consturctor = tb.Type.GetConstructor(new Type[0]); - parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; - for (var idx = 0; idx < map.Count; idx++) { - var child = new ReadAnonymousTypeInfo { - Property = tb.Properties.TryGetValue(map[idx].Column.CsName, out var tryprop) ? tryprop : tb.Type.GetProperty(map[idx].Column.CsName, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance), - CsName = map[idx].Column.CsName, DbField = $"{map[idx].Table.Alias}.{_common.QuoteSqlName(map[idx].Column.Attribute.Name)}", - CsType = map[idx].Column.CsType, - MapType = map[idx].Column.Attribute.MapType - }; - field.Append(", ").Append(_common.QuoteReadColumn(child.MapType, child.DbField)); - if (index >= 0) field.Append(" as").Append(++index); - parent.Childs.Add(child); - } - } else { - parent.CsType = exp.Type; - parent.DbField = ExpressionLambdaToSql(exp, getTSC()); - field.Append(", ").Append(parent.DbField); - if (index >= 0) field.Append(" as").Append(++index); - parent.MapType = SearchColumnByField(_tables, null, parent.DbField)?.Attribute.MapType ?? exp.Type; - return false; - } - return false; - case ExpressionType.MemberInit: - var initExp = exp as MemberInitExpression; - parent.Consturctor = initExp.NewExpression.Type.GetConstructors()[0]; - parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; - if (initExp.Bindings?.Count > 0) { - //指定 dto映射 - for (var a = 0; a < initExp.Bindings.Count; a++) { - var initAssignExp = (initExp.Bindings[a] as MemberAssignment); - if (initAssignExp == null) continue; - var child = new ReadAnonymousTypeInfo { - Property = initExp.Type.GetProperty(initExp.Bindings[a].Member.Name, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance), - CsName = initExp.Bindings[a].Member.Name, - CsType = initAssignExp.Expression.Type, - MapType = initAssignExp.Expression.Type - }; - parent.Childs.Add(child); - ReadAnonymousField(_tables, field, child, ref index, initAssignExp.Expression, getSelectGroupingMapString); - } - } else { - //dto 映射 - var dtoProps = _dicReadAnonymousFieldDtoPropertys.GetOrAdd(initExp.NewExpression.Type, dtoType => dtoType.GetProperties()); - foreach (var dtoProp in dtoProps) { - foreach (var dtTb in _tables) { - if (dtTb.Table.Columns.TryGetValue(dtoProp.Name, out var trydtocol)) { - var child = new ReadAnonymousTypeInfo { - Property = dtoProp, - CsName = dtoProp.Name, - CsType = dtoProp.PropertyType, - MapType = trydtocol.Attribute.MapType - }; - parent.Childs.Add(child); - if (dtTb.Parameter != null) - ReadAnonymousField(_tables, field, child, ref index, Expression.Property(dtTb.Parameter, dtTb.Table.Properties[trydtocol.CsName]), getSelectGroupingMapString); - else { - child.DbField = $"{dtTb.Alias}.{_common.QuoteSqlName(trydtocol.Attribute.Name)}"; - field.Append(", ").Append(child.DbField); - if (index >= 0) field.Append(" as").Append(++index); - } - break; - } - } - } - if (parent.Childs.Any() == false) throw new Exception($"映射异常:{initExp.NewExpression.Type.Name} 没有一个属性名相同"); - } - return true; - case ExpressionType.New: - var newExp = exp as NewExpression; - parent.Consturctor = newExp.Type.GetConstructors()[0]; - parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Arguments; - if (newExp.Members?.Count > 0) { - for (var a = 0; a < newExp.Members.Count; a++) { - var child = new ReadAnonymousTypeInfo { - Property = newExp.Type.GetProperty(newExp.Members[a].Name, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance), - CsName = newExp.Members[a].Name, - CsType = newExp.Arguments[a].Type, - MapType = newExp.Arguments[a].Type - }; - parent.Childs.Add(child); - ReadAnonymousField(_tables, field, child, ref index, newExp.Arguments[a], getSelectGroupingMapString); - } - } else { - //dto 映射 - parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; - var dtoProps = _dicReadAnonymousFieldDtoPropertys.GetOrAdd(newExp.Type, dtoType => dtoType.GetProperties()); - foreach (var dtoProp in dtoProps) { - foreach(var dtTb in _tables) { - if (dtTb.Table.ColumnsByCs.TryGetValue(dtoProp.Name, out var trydtocol)) { - var child = new ReadAnonymousTypeInfo { - Property = dtoProp, - CsName = dtoProp.Name, - CsType = dtoProp.PropertyType, - MapType = trydtocol.Attribute.MapType - }; - parent.Childs.Add(child); - if (dtTb.Parameter != null) - ReadAnonymousField(_tables, field, child, ref index, Expression.Property(dtTb.Parameter, dtTb.Table.Properties[trydtocol.CsName]), getSelectGroupingMapString); - else { - child.DbField = $"{dtTb.Alias}.{_common.QuoteSqlName(trydtocol.Attribute.Name)}"; - field.Append(", ").Append(child.DbField); - if (index >= 0) field.Append(" as").Append(++index); - } - break; - } - } - } - if (parent.Childs.Any() == false) throw new Exception($"映射异常:{newExp.Type.Name} 没有一个属性名相同"); - } - return true; - } - parent.DbField = $"({ExpressionLambdaToSql(exp, getTSC())})"; - field.Append(", ").Append(parent.DbField); - if (index >= 0) field.Append(" as").Append(++index); - return false; - } - public object ReadAnonymous(ReadAnonymousTypeInfo parent, DbDataReader dr, ref int index, bool notRead) { - if (parent.Childs.Any() == false) { - if (notRead) { - ++index; - return Utils.GetDataReaderValue(parent.CsType, null); - } - if (parent.CsType == parent.MapType) - return Utils.GetDataReaderValue(parent.CsType, dr.GetValue(++index)); - return Utils.GetDataReaderValue(parent.CsType, Utils.GetDataReaderValue(parent.MapType, dr.GetValue(++index))); - } - switch (parent.ConsturctorType) { - case ReadAnonymousTypeInfoConsturctorType.Arguments: - var args = new object[parent.Childs.Count]; - for (var a = 0; a < parent.Childs.Count; a++) { - var objval = ReadAnonymous(parent.Childs[a], dr, ref index, notRead); - if (notRead == false) - args[a] = objval; - } - return parent.Consturctor.Invoke(args); - case ReadAnonymousTypeInfoConsturctorType.Properties: - var ret = parent.Consturctor.Invoke(null); - var isnull = notRead; - for (var b = 0; b < parent.Childs.Count; b++) { - var prop = parent.Childs[b].Property; - var objval = ReadAnonymous(parent.Childs[b], dr, ref index, notRead); - if (isnull == false && objval == null && parent.Table != null && parent.Table.ColumnsByCs.TryGetValue(parent.Childs[b].CsName, out var trycol) && trycol.Attribute.IsPrimary) - isnull = true; - if (isnull == false) - prop.SetValue(ret, objval, null); - } - return isnull ? null : ret; - } - return null; - } + static ConcurrentDictionary _dicReadAnonymousFieldDtoPropertys = new ConcurrentDictionary(); + public bool ReadAnonymousField(List _tables, StringBuilder field, ReadAnonymousTypeInfo parent, ref int index, Expression exp, Func getSelectGroupingMapString) + { + Func getTSC = () => new ExpTSC { _tables = _tables, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where }; + switch (exp.NodeType) + { + case ExpressionType.Quote: return ReadAnonymousField(_tables, field, parent, ref index, (exp as UnaryExpression)?.Operand, getSelectGroupingMapString); + case ExpressionType.Lambda: return ReadAnonymousField(_tables, field, parent, ref index, (exp as LambdaExpression)?.Body, getSelectGroupingMapString); + case ExpressionType.Negate: + case ExpressionType.NegateChecked: + parent.DbField = $"-({ExpressionLambdaToSql(exp, getTSC())})"; + field.Append(", ").Append(parent.DbField); + if (index >= 0) field.Append(" as").Append(++index); + return false; + case ExpressionType.Convert: return ReadAnonymousField(_tables, field, parent, ref index, (exp as UnaryExpression)?.Operand, getSelectGroupingMapString); + case ExpressionType.Constant: + var constExp = exp as ConstantExpression; + //处理自定义SQL语句,如: ToList(new { + // ccc = "now()", + // partby = "sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)" + //}),有缺点即 ccc partby 接受类型都是 string,可配合 Convert.ToXxx 类型转换,请看下面的兼容 + parent.DbField = constExp.Type.FullName == "System.String" ? (constExp.Value?.ToString() ?? "NULL") : _common.FormatSql("{0}", constExp?.Value); + field.Append(", ").Append(parent.DbField); + if (index >= 0) field.Append(" as").Append(++index); + return false; + case ExpressionType.Call: + var callExp = exp as MethodCallExpression; + //处理自定义SQL语句,如: ToList(new { + // ccc = Convert.ToDateTime("now()"), + // partby = Convert.ToDecimal("sum(num) over(PARTITION BY server_id,os,rid,chn order by id desc)") + //}) + if (callExp.Method?.DeclaringType.FullName == "System.Convert" && + callExp.Method.Name.StartsWith("To") && + callExp.Arguments[0].NodeType == ExpressionType.Constant && + callExp.Arguments[0].Type.FullName == "System.String") + parent.DbField = (callExp.Arguments[0] as ConstantExpression).Value?.ToString() ?? "NULL"; + else + parent.DbField = ExpressionLambdaToSql(exp, getTSC()); + field.Append(", ").Append(parent.DbField); + if (index >= 0) field.Append(" as").Append(++index); + return false; + case ExpressionType.Parameter: + case ExpressionType.MemberAccess: + if (_common.GetTableByEntity(exp.Type) != null) + { //加载表所有字段 + var map = new List(); + ExpressionSelectColumn_MemberAccess(_tables, map, SelectTableInfoType.From, exp, true, getSelectGroupingMapString); + var tb = parent.Table = map.First().Table.Table; + parent.Consturctor = tb.Type.GetConstructor(new Type[0]); + parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; + for (var idx = 0; idx < map.Count; idx++) + { + var child = new ReadAnonymousTypeInfo + { + Property = tb.Properties.TryGetValue(map[idx].Column.CsName, out var tryprop) ? tryprop : tb.Type.GetProperty(map[idx].Column.CsName, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance), + CsName = map[idx].Column.CsName, + DbField = $"{map[idx].Table.Alias}.{_common.QuoteSqlName(map[idx].Column.Attribute.Name)}", + CsType = map[idx].Column.CsType, + MapType = map[idx].Column.Attribute.MapType + }; + field.Append(", ").Append(_common.QuoteReadColumn(child.MapType, child.DbField)); + if (index >= 0) field.Append(" as").Append(++index); + parent.Childs.Add(child); + } + } + else + { + parent.CsType = exp.Type; + parent.DbField = ExpressionLambdaToSql(exp, getTSC()); + field.Append(", ").Append(parent.DbField); + if (index >= 0) field.Append(" as").Append(++index); + parent.MapType = SearchColumnByField(_tables, null, parent.DbField)?.Attribute.MapType ?? exp.Type; + return false; + } + return false; + case ExpressionType.MemberInit: + var initExp = exp as MemberInitExpression; + parent.Consturctor = initExp.NewExpression.Type.GetConstructors()[0]; + parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; + if (initExp.Bindings?.Count > 0) + { + //指定 dto映射 + for (var a = 0; a < initExp.Bindings.Count; a++) + { + var initAssignExp = (initExp.Bindings[a] as MemberAssignment); + if (initAssignExp == null) continue; + var child = new ReadAnonymousTypeInfo + { + Property = initExp.Type.GetProperty(initExp.Bindings[a].Member.Name, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance), + CsName = initExp.Bindings[a].Member.Name, + CsType = initAssignExp.Expression.Type, + MapType = initAssignExp.Expression.Type + }; + parent.Childs.Add(child); + ReadAnonymousField(_tables, field, child, ref index, initAssignExp.Expression, getSelectGroupingMapString); + } + } + else + { + //dto 映射 + var dtoProps = _dicReadAnonymousFieldDtoPropertys.GetOrAdd(initExp.NewExpression.Type, dtoType => dtoType.GetProperties()); + foreach (var dtoProp in dtoProps) + { + foreach (var dtTb in _tables) + { + if (dtTb.Table.Columns.TryGetValue(dtoProp.Name, out var trydtocol)) + { + var child = new ReadAnonymousTypeInfo + { + Property = dtoProp, + CsName = dtoProp.Name, + CsType = dtoProp.PropertyType, + MapType = trydtocol.Attribute.MapType + }; + parent.Childs.Add(child); + if (dtTb.Parameter != null) + ReadAnonymousField(_tables, field, child, ref index, Expression.Property(dtTb.Parameter, dtTb.Table.Properties[trydtocol.CsName]), getSelectGroupingMapString); + else + { + child.DbField = $"{dtTb.Alias}.{_common.QuoteSqlName(trydtocol.Attribute.Name)}"; + field.Append(", ").Append(child.DbField); + if (index >= 0) field.Append(" as").Append(++index); + } + break; + } + } + } + if (parent.Childs.Any() == false) throw new Exception($"映射异常:{initExp.NewExpression.Type.Name} 没有一个属性名相同"); + } + return true; + case ExpressionType.New: + var newExp = exp as NewExpression; + parent.Consturctor = newExp.Type.GetConstructors()[0]; + parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Arguments; + if (newExp.Members?.Count > 0) + { + for (var a = 0; a < newExp.Members.Count; a++) + { + var child = new ReadAnonymousTypeInfo + { + Property = newExp.Type.GetProperty(newExp.Members[a].Name, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance), + CsName = newExp.Members[a].Name, + CsType = newExp.Arguments[a].Type, + MapType = newExp.Arguments[a].Type + }; + parent.Childs.Add(child); + ReadAnonymousField(_tables, field, child, ref index, newExp.Arguments[a], getSelectGroupingMapString); + } + } + else + { + //dto 映射 + parent.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; + var dtoProps = _dicReadAnonymousFieldDtoPropertys.GetOrAdd(newExp.Type, dtoType => dtoType.GetProperties()); + foreach (var dtoProp in dtoProps) + { + foreach (var dtTb in _tables) + { + if (dtTb.Table.ColumnsByCs.TryGetValue(dtoProp.Name, out var trydtocol)) + { + var child = new ReadAnonymousTypeInfo + { + Property = dtoProp, + CsName = dtoProp.Name, + CsType = dtoProp.PropertyType, + MapType = trydtocol.Attribute.MapType + }; + parent.Childs.Add(child); + if (dtTb.Parameter != null) + ReadAnonymousField(_tables, field, child, ref index, Expression.Property(dtTb.Parameter, dtTb.Table.Properties[trydtocol.CsName]), getSelectGroupingMapString); + else + { + child.DbField = $"{dtTb.Alias}.{_common.QuoteSqlName(trydtocol.Attribute.Name)}"; + field.Append(", ").Append(child.DbField); + if (index >= 0) field.Append(" as").Append(++index); + } + break; + } + } + } + if (parent.Childs.Any() == false) throw new Exception($"映射异常:{newExp.Type.Name} 没有一个属性名相同"); + } + return true; + } + parent.DbField = $"({ExpressionLambdaToSql(exp, getTSC())})"; + field.Append(", ").Append(parent.DbField); + if (index >= 0) field.Append(" as").Append(++index); + return false; + } + public object ReadAnonymous(ReadAnonymousTypeInfo parent, DbDataReader dr, ref int index, bool notRead) + { + if (parent.Childs.Any() == false) + { + if (notRead) + { + ++index; + return Utils.GetDataReaderValue(parent.CsType, null); + } + if (parent.CsType == parent.MapType) + return Utils.GetDataReaderValue(parent.CsType, dr.GetValue(++index)); + return Utils.GetDataReaderValue(parent.CsType, Utils.GetDataReaderValue(parent.MapType, dr.GetValue(++index))); + } + switch (parent.ConsturctorType) + { + case ReadAnonymousTypeInfoConsturctorType.Arguments: + var args = new object[parent.Childs.Count]; + for (var a = 0; a < parent.Childs.Count; a++) + { + var objval = ReadAnonymous(parent.Childs[a], dr, ref index, notRead); + if (notRead == false) + args[a] = objval; + } + return parent.Consturctor.Invoke(args); + case ReadAnonymousTypeInfoConsturctorType.Properties: + var ret = parent.Consturctor.Invoke(null); + var isnull = notRead; + for (var b = 0; b < parent.Childs.Count; b++) + { + var prop = parent.Childs[b].Property; + var objval = ReadAnonymous(parent.Childs[b], dr, ref index, notRead); + if (isnull == false && objval == null && parent.Table != null && parent.Table.ColumnsByCs.TryGetValue(parent.Childs[b].CsName, out var trycol) && trycol.Attribute.IsPrimary) + isnull = true; + if (isnull == false) + prop.SetValue(ret, objval, null); + } + return isnull ? null : ret; + } + return null; + } - public ColumnInfo SearchColumnByField(List _tables, TableInfo currentTable, string field) { - if (_tables != null) { - var testCol = _common.TrimQuoteSqlName(field).Split(new[] { '.' }, 2); - if (testCol.Length == 2) { - var testTb = _tables.Where(a => a.Alias == testCol[0]).ToArray(); - if (testTb.Length == 1 && testTb[0].Table.Columns.TryGetValue(testCol[1], out var trytstcol)) - return trytstcol; - } - } - if (currentTable != null) { - var testCol = _common.TrimQuoteSqlName(field); - if (currentTable.Columns.TryGetValue(testCol, out var trytstcol)) - return trytstcol; - } - return null; - } + public ColumnInfo SearchColumnByField(List _tables, TableInfo currentTable, string field) + { + if (_tables != null) + { + var testCol = _common.TrimQuoteSqlName(field).Split(new[] { '.' }, 2); + if (testCol.Length == 2) + { + var testTb = _tables.Where(a => a.Alias == testCol[0]).ToArray(); + if (testTb.Length == 1 && testTb[0].Table.Columns.TryGetValue(testCol[1], out var trytstcol)) + return trytstcol; + } + } + if (currentTable != null) + { + var testCol = _common.TrimQuoteSqlName(field); + if (currentTable.Columns.TryGetValue(testCol, out var trytstcol)) + return trytstcol; + } + return null; + } - public string ExpressionSelectColumn_MemberAccess(List _tables, List _selectColumnMap, SelectTableInfoType tbtype, Expression exp, bool isQuoteName, Func getSelectGroupingMapString) { - return ExpressionLambdaToSql(exp, new ExpTSC { _tables = _tables, _selectColumnMap = _selectColumnMap, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = tbtype, isQuoteName = isQuoteName, isDisableDiyParse = false, style = ExpressionStyle.SelectColumns }); - } + public string ExpressionSelectColumn_MemberAccess(List _tables, List _selectColumnMap, SelectTableInfoType tbtype, Expression exp, bool isQuoteName, Func getSelectGroupingMapString) + { + return ExpressionLambdaToSql(exp, new ExpTSC { _tables = _tables, _selectColumnMap = _selectColumnMap, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = tbtype, isQuoteName = isQuoteName, isDisableDiyParse = false, style = ExpressionStyle.SelectColumns }); + } - public string[] ExpressionSelectColumns_MemberAccess_New_NewArrayInit(List _tables, Expression exp, bool isQuoteName, Func getSelectGroupingMapString) { - switch (exp?.NodeType) { - case ExpressionType.Quote: return ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, (exp as UnaryExpression)?.Operand, isQuoteName, getSelectGroupingMapString); - case ExpressionType.Lambda: return ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, (exp as LambdaExpression)?.Body, isQuoteName, getSelectGroupingMapString); - case ExpressionType.Convert: return ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, (exp as UnaryExpression)?.Operand, isQuoteName, getSelectGroupingMapString); - case ExpressionType.Constant: return new[] { ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, isQuoteName, getSelectGroupingMapString) }; - case ExpressionType.MemberAccess: return new[] { ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, isQuoteName, getSelectGroupingMapString) }; - case ExpressionType.New: - var newExp = exp as NewExpression; - if (newExp == null) break; - var newExpMembers = new string[newExp.Members.Count]; - for (var a = 0; a < newExpMembers.Length; a++) newExpMembers[a] = ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, newExp.Arguments[a], isQuoteName, getSelectGroupingMapString); - return newExpMembers; - case ExpressionType.NewArrayInit: - var newArr = exp as NewArrayExpression; - if (newArr == null) break; - var newArrMembers = new List(); - foreach (var newArrExp in newArr.Expressions) newArrMembers.AddRange(ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, newArrExp, isQuoteName, getSelectGroupingMapString)); - return newArrMembers.ToArray(); - } - return new string[0]; - } + public string[] ExpressionSelectColumns_MemberAccess_New_NewArrayInit(List _tables, Expression exp, bool isQuoteName, Func getSelectGroupingMapString) + { + switch (exp?.NodeType) + { + case ExpressionType.Quote: return ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, (exp as UnaryExpression)?.Operand, isQuoteName, getSelectGroupingMapString); + case ExpressionType.Lambda: return ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, (exp as LambdaExpression)?.Body, isQuoteName, getSelectGroupingMapString); + case ExpressionType.Convert: return ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, (exp as UnaryExpression)?.Operand, isQuoteName, getSelectGroupingMapString); + case ExpressionType.Constant: return new[] { ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, isQuoteName, getSelectGroupingMapString) }; + case ExpressionType.MemberAccess: return new[] { ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, isQuoteName, getSelectGroupingMapString) }; + case ExpressionType.New: + var newExp = exp as NewExpression; + if (newExp == null) break; + var newExpMembers = new string[newExp.Members.Count]; + for (var a = 0; a < newExpMembers.Length; a++) newExpMembers[a] = ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, newExp.Arguments[a], isQuoteName, getSelectGroupingMapString); + return newExpMembers; + case ExpressionType.NewArrayInit: + var newArr = exp as NewArrayExpression; + if (newArr == null) break; + var newArrMembers = new List(); + foreach (var newArrExp in newArr.Expressions) newArrMembers.AddRange(ExpressionSelectColumns_MemberAccess_New_NewArrayInit(_tables, newArrExp, isQuoteName, getSelectGroupingMapString)); + return newArrMembers.ToArray(); + } + return new string[0]; + } - static readonly Dictionary dicExpressionOperator = new Dictionary() { - { ExpressionType.OrElse, "OR" }, - { ExpressionType.Or, "|" }, - { ExpressionType.AndAlso, "AND" }, - { ExpressionType.And, "&" }, - { ExpressionType.GreaterThan, ">" }, - { ExpressionType.GreaterThanOrEqual, ">=" }, - { ExpressionType.LessThan, "<" }, - { ExpressionType.LessThanOrEqual, "<=" }, - { ExpressionType.NotEqual, "<>" }, - { ExpressionType.Add, "+" }, - { ExpressionType.Subtract, "-" }, - { ExpressionType.Multiply, "*" }, - { ExpressionType.Divide, "/" }, - { ExpressionType.Modulo, "%" }, - { ExpressionType.Equal, "=" }, - }; - public string ExpressionWhereLambdaNoneForeignObject(List _tables, TableInfo table, List _selectColumnMap, Expression exp, Func getSelectGroupingMapString) { - var sql = ExpressionLambdaToSql(exp, new ExpTSC { _tables = _tables, _selectColumnMap = _selectColumnMap, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where, currentTable = table }); - var isBool = exp.Type.NullableTypeOrThis() == typeof(bool); - if (exp.NodeType == ExpressionType.MemberAccess && isBool && sql.Contains(" IS ") == false && sql.Contains(" = ") == false) - return $"{sql} = {formatSql(true, null)}"; - if (isBool) { - switch (sql) { - case "1": - case "'t'": return "1=1"; - case "0": - case "'f'": return "1=2"; - default: return sql; - } - } - return sql; - } + static readonly Dictionary dicExpressionOperator = new Dictionary() { + { ExpressionType.OrElse, "OR" }, + { ExpressionType.Or, "|" }, + { ExpressionType.AndAlso, "AND" }, + { ExpressionType.And, "&" }, + { ExpressionType.GreaterThan, ">" }, + { ExpressionType.GreaterThanOrEqual, ">=" }, + { ExpressionType.LessThan, "<" }, + { ExpressionType.LessThanOrEqual, "<=" }, + { ExpressionType.NotEqual, "<>" }, + { ExpressionType.Add, "+" }, + { ExpressionType.Subtract, "-" }, + { ExpressionType.Multiply, "*" }, + { ExpressionType.Divide, "/" }, + { ExpressionType.Modulo, "%" }, + { ExpressionType.Equal, "=" }, + }; + public string ExpressionWhereLambdaNoneForeignObject(List _tables, TableInfo table, List _selectColumnMap, Expression exp, Func getSelectGroupingMapString) + { + var sql = ExpressionLambdaToSql(exp, new ExpTSC { _tables = _tables, _selectColumnMap = _selectColumnMap, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where, currentTable = table }); + var isBool = exp.Type.NullableTypeOrThis() == typeof(bool); + if (exp.NodeType == ExpressionType.MemberAccess && isBool && sql.Contains(" IS ") == false && sql.Contains(" = ") == false) + return $"{sql} = {formatSql(true, null)}"; + if (isBool) + { + switch (sql) + { + case "1": + case "'t'": return "1=1"; + case "0": + case "'f'": return "1=2"; + default: return sql; + } + } + return sql; + } - public string ExpressionWhereLambda(List _tables, Expression exp, Func getSelectGroupingMapString) { - var sql = ExpressionLambdaToSql(exp, new ExpTSC { _tables = _tables, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where }); - var isBool = exp.Type.NullableTypeOrThis() == typeof(bool); - if (exp.NodeType == ExpressionType.MemberAccess && isBool && sql.Contains(" IS ") == false && sql.Contains(" = ") == false) - return $"{sql} = {formatSql(true, null)}"; - if (isBool) { - switch (sql) { - case "1": - case "'t'": return "1=1"; - case "0": - case "'f'": return "1=2"; - default: return sql; - } - } - return sql; - } - public void ExpressionJoinLambda(List _tables, SelectTableInfoType tbtype, Expression exp, Func getSelectGroupingMapString) { - var tbidx = _tables.Count; - var sql = ExpressionLambdaToSql(exp, new ExpTSC { _tables = _tables, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = tbtype, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where }); - var isBool = exp.Type.NullableTypeOrThis() == typeof(bool); - if (exp.NodeType == ExpressionType.MemberAccess && isBool && sql.Contains(" IS ") == false && sql.Contains(" = ") == false) - sql = $"{sql} = {formatSql(true, null)}"; - if (isBool) { - switch (sql) { - case "1": - case "'t'": sql = "1=1"; break; - case "0": - case "'f'": sql = "1=2"; break; - default: break; - } - } - if (_tables.Count > tbidx) { - _tables[tbidx].Type = tbtype; - _tables[tbidx].On = sql; - for (var a = tbidx + 1; a < _tables.Count; a++) - _tables[a].Type = SelectTableInfoType.From; - } else { - var find = _tables.Where((a, c) => c > 0 && (a.Type == tbtype || a.Type == SelectTableInfoType.From) && string.IsNullOrEmpty(a.On)).LastOrDefault(); - if (find != null) { - find.Type = tbtype; - find.On = sql; - } - } - } - static ConcurrentDictionary _dicExpressionLambdaToSqlAsSelectMethodInfo = new ConcurrentDictionary(); - static ConcurrentDictionary _dicExpressionLambdaToSqlAsSelectWhereMethodInfo = new ConcurrentDictionary(); - static ConcurrentDictionary _dicExpressionLambdaToSqlAsSelectWhereSqlMethodInfo = new ConcurrentDictionary(); - static ConcurrentDictionary _dicExpressionLambdaToSqlAsSelectAnyMethodInfo = new ConcurrentDictionary(); - internal static ConcurrentDictionary _dicNullableValueProperty = new ConcurrentDictionary(); - static ConcurrentDictionary _dicFreeSqlGlobalExtensionsAsSelectExpression = new ConcurrentDictionary(); - static MethodInfo MethodDateTimeSubtractDateTime = typeof(DateTime).GetMethod("Subtract", new Type[] { typeof(DateTime) }); - static MethodInfo MethodDateTimeSubtractTimeSpan = typeof(DateTime).GetMethod("Subtract", new Type[] { typeof(TimeSpan) }); + public string ExpressionWhereLambda(List _tables, Expression exp, Func getSelectGroupingMapString) + { + var sql = ExpressionLambdaToSql(exp, new ExpTSC { _tables = _tables, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where }); + var isBool = exp.Type.NullableTypeOrThis() == typeof(bool); + if (exp.NodeType == ExpressionType.MemberAccess && isBool && sql.Contains(" IS ") == false && sql.Contains(" = ") == false) + return $"{sql} = {formatSql(true, null)}"; + if (isBool) + { + switch (sql) + { + case "1": + case "'t'": return "1=1"; + case "0": + case "'f'": return "1=2"; + default: return sql; + } + } + return sql; + } + public void ExpressionJoinLambda(List _tables, SelectTableInfoType tbtype, Expression exp, Func getSelectGroupingMapString) + { + var tbidx = _tables.Count; + var sql = ExpressionLambdaToSql(exp, new ExpTSC { _tables = _tables, getSelectGroupingMapString = getSelectGroupingMapString, tbtype = tbtype, isQuoteName = true, isDisableDiyParse = false, style = ExpressionStyle.Where }); + var isBool = exp.Type.NullableTypeOrThis() == typeof(bool); + if (exp.NodeType == ExpressionType.MemberAccess && isBool && sql.Contains(" IS ") == false && sql.Contains(" = ") == false) + sql = $"{sql} = {formatSql(true, null)}"; + if (isBool) + { + switch (sql) + { + case "1": + case "'t'": sql = "1=1"; break; + case "0": + case "'f'": sql = "1=2"; break; + default: break; + } + } + if (_tables.Count > tbidx) + { + _tables[tbidx].Type = tbtype; + _tables[tbidx].On = sql; + for (var a = tbidx + 1; a < _tables.Count; a++) + _tables[a].Type = SelectTableInfoType.From; + } + else + { + var find = _tables.Where((a, c) => c > 0 && (a.Type == tbtype || a.Type == SelectTableInfoType.From) && string.IsNullOrEmpty(a.On)).LastOrDefault(); + if (find != null) + { + find.Type = tbtype; + find.On = sql; + } + } + } + static ConcurrentDictionary _dicExpressionLambdaToSqlAsSelectMethodInfo = new ConcurrentDictionary(); + static ConcurrentDictionary _dicExpressionLambdaToSqlAsSelectWhereMethodInfo = new ConcurrentDictionary(); + static ConcurrentDictionary _dicExpressionLambdaToSqlAsSelectWhereSqlMethodInfo = new ConcurrentDictionary(); + static ConcurrentDictionary _dicExpressionLambdaToSqlAsSelectAnyMethodInfo = new ConcurrentDictionary(); + internal static ConcurrentDictionary _dicNullableValueProperty = new ConcurrentDictionary(); + static ConcurrentDictionary _dicFreeSqlGlobalExtensionsAsSelectExpression = new ConcurrentDictionary(); + static MethodInfo MethodDateTimeSubtractDateTime = typeof(DateTime).GetMethod("Subtract", new Type[] { typeof(DateTime) }); + static MethodInfo MethodDateTimeSubtractTimeSpan = typeof(DateTime).GetMethod("Subtract", new Type[] { typeof(TimeSpan) }); - public string ExpressionBinary(string oper, Expression leftExp, Expression rightExp, ExpTSC tsc) { - switch (oper) { - case "OR": - case "|": - case "&": - case "+": - case "-": - if (oper == "+" && (leftExp.Type == typeof(string) || rightExp.Type == typeof(string))) - return _common.StringConcat(new[] { ExpressionLambdaToSql(leftExp, tsc), ExpressionLambdaToSql(rightExp, tsc) }, new[] { leftExp.Type, rightExp.Type }); - if (oper == "-" && leftExp.Type.NullableTypeOrThis() == typeof(DateTime)) { - if (rightExp.Type.NullableTypeOrThis() == typeof(DateTime)) - return ExpressionLambdaToSql(Expression.Call(leftExp, MethodDateTimeSubtractDateTime, rightExp), tsc); - if (rightExp.Type.NullableTypeOrThis() == typeof(TimeSpan)) - return ExpressionLambdaToSql(Expression.Call(leftExp, MethodDateTimeSubtractTimeSpan, rightExp), tsc); - } - return $"({ExpressionLambdaToSql(leftExp, tsc)} {oper} {ExpressionLambdaToSql(rightExp, tsc)})"; - } + public string ExpressionBinary(string oper, Expression leftExp, Expression rightExp, ExpTSC tsc) + { + switch (oper) + { + case "OR": + case "|": + case "&": + case "+": + case "-": + if (oper == "+" && (leftExp.Type == typeof(string) || rightExp.Type == typeof(string))) + return _common.StringConcat(new[] { ExpressionLambdaToSql(leftExp, tsc), ExpressionLambdaToSql(rightExp, tsc) }, new[] { leftExp.Type, rightExp.Type }); + if (oper == "-" && leftExp.Type.NullableTypeOrThis() == typeof(DateTime)) + { + if (rightExp.Type.NullableTypeOrThis() == typeof(DateTime)) + return ExpressionLambdaToSql(Expression.Call(leftExp, MethodDateTimeSubtractDateTime, rightExp), tsc); + if (rightExp.Type.NullableTypeOrThis() == typeof(TimeSpan)) + return ExpressionLambdaToSql(Expression.Call(leftExp, MethodDateTimeSubtractTimeSpan, rightExp), tsc); + } + return $"({ExpressionLambdaToSql(leftExp, tsc)} {oper} {ExpressionLambdaToSql(rightExp, tsc)})"; + } - var left = ExpressionLambdaToSql(leftExp, tsc); - var leftMapColumn = SearchColumnByField(tsc._tables, tsc.currentTable, left); - var isLeftMapType = leftMapColumn != null && (leftMapColumn.Attribute.MapType != rightExp.Type || leftMapColumn.CsType != rightExp.Type); - ColumnInfo rightMapColumn = null; - var isRightMapType = false; - if (isLeftMapType) tsc.mapType = leftMapColumn.Attribute.MapType; + var left = ExpressionLambdaToSql(leftExp, tsc); + var leftMapColumn = SearchColumnByField(tsc._tables, tsc.currentTable, left); + var isLeftMapType = leftMapColumn != null && (leftMapColumn.Attribute.MapType != rightExp.Type || leftMapColumn.CsType != rightExp.Type); + ColumnInfo rightMapColumn = null; + var isRightMapType = false; + if (isLeftMapType) tsc.mapType = leftMapColumn.Attribute.MapType; - var right = ExpressionLambdaToSql(rightExp, tsc); - if (right != "NULL" && isLeftMapType) { - var enumType = leftMapColumn.CsType.NullableTypeOrThis(); - if (enumType.IsEnum) - right = formatSql(Enum.Parse(enumType, right.Trim('\'')), leftMapColumn.Attribute.MapType); - } - if (leftMapColumn == null) { - rightMapColumn = SearchColumnByField(tsc._tables, tsc.currentTable, right); - isRightMapType = rightMapColumn != null && (rightMapColumn.Attribute.MapType != leftExp.Type || rightMapColumn.CsType != leftExp.Type); - if (isRightMapType) { - tsc.mapType = rightMapColumn.Attribute.MapType; - left = ExpressionLambdaToSql(leftExp, tsc); - if (left != "NULL" && isRightMapType) { - var enumType = rightMapColumn.CsType.NullableTypeOrThis(); - if (enumType.IsEnum) - left = formatSql(Enum.Parse(enumType, left.Trim('\'')), rightMapColumn.Attribute.MapType); - } - } - } - if (leftExp.Type.NullableTypeOrThis() == typeof(bool) && (leftExp.NodeType != ExpressionType.MemberAccess && rightExp.NodeType != ExpressionType.MemberAccess)) { - if (oper == "=") { - var trueVal = formatSql(true, null); - var falseVal = formatSql(false, null); - if (left == trueVal) return right; - else if (left == falseVal) return $"not({right})"; - else if (right == trueVal) return left; - else if (right == falseVal) return $"not({left})"; - } else if (oper == "<>") { - var trueVal = formatSql(true, null); - var falseVal = formatSql(false, null); - if (left == trueVal) return $"not({right})"; - else if (left == falseVal) return right; - else if (right == trueVal) return $"not({left})"; - else if (right == falseVal) return left; - } - } + var right = ExpressionLambdaToSql(rightExp, tsc); + if (right != "NULL" && isLeftMapType) + { + var enumType = leftMapColumn.CsType.NullableTypeOrThis(); + if (enumType.IsEnum) + right = formatSql(Enum.Parse(enumType, right.Trim('\'')), leftMapColumn.Attribute.MapType); + } + if (leftMapColumn == null) + { + rightMapColumn = SearchColumnByField(tsc._tables, tsc.currentTable, right); + isRightMapType = rightMapColumn != null && (rightMapColumn.Attribute.MapType != leftExp.Type || rightMapColumn.CsType != leftExp.Type); + if (isRightMapType) + { + tsc.mapType = rightMapColumn.Attribute.MapType; + left = ExpressionLambdaToSql(leftExp, tsc); + if (left != "NULL" && isRightMapType) + { + var enumType = rightMapColumn.CsType.NullableTypeOrThis(); + if (enumType.IsEnum) + left = formatSql(Enum.Parse(enumType, left.Trim('\'')), rightMapColumn.Attribute.MapType); + } + } + } + if (leftExp.Type.NullableTypeOrThis() == typeof(bool) && (leftExp.NodeType != ExpressionType.MemberAccess && rightExp.NodeType != ExpressionType.MemberAccess)) + { + if (oper == "=") + { + var trueVal = formatSql(true, null); + var falseVal = formatSql(false, null); + if (left == trueVal) return right; + else if (left == falseVal) return $"not({right})"; + else if (right == trueVal) return left; + else if (right == falseVal) return $"not({left})"; + } + else if (oper == "<>") + { + var trueVal = formatSql(true, null); + var falseVal = formatSql(false, null); + if (left == trueVal) return $"not({right})"; + else if (left == falseVal) return right; + else if (right == trueVal) return $"not({left})"; + else if (right == falseVal) return left; + } + } - if (left == "NULL") { - var tmp = right; - right = left; - left = tmp; - } - if (right == "NULL") oper = oper == "=" ? " IS " : " IS NOT "; - if (oper == "%") return _common.Mod(left, right, leftExp.Type, rightExp.Type); - tsc.mapType = null; - return $"{left} {oper} {right}"; - } - public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) { - if (exp == null) return ""; - if (tsc.isDisableDiyParse == false && _common._orm.Aop.ParseExpression != null) { - var args = new Aop.ParseExpressionEventArgs(exp, ukexp => ExpressionLambdaToSql(ukexp, tsc.CloneDisableDiyParse())); - _common._orm.Aop.ParseExpression?.Invoke(this, args); - if (string.IsNullOrEmpty(args.Result) == false) return args.Result; - } - switch (exp.NodeType) { - case ExpressionType.Not: - var notExp = (exp as UnaryExpression)?.Operand; - if (notExp.NodeType == ExpressionType.MemberAccess) { - var notBody = ExpressionLambdaToSql(notExp, tsc); - if (notBody.Contains(" IS NULL")) return notBody.Replace(" IS NULL", " IS NOT NULL"); - if (notBody.Contains(" IS NOT NULL")) return notBody.Replace(" IS NOT NULL", " IS NULL"); - if (notBody.Contains("=")) return notBody.Replace("=", "!="); - if (notBody.Contains("!=")) return notBody.Replace("!=", "="); - return $"{notBody} = {formatSql(false, null)}"; - } - return $"not({ExpressionLambdaToSql(notExp, tsc)})"; - case ExpressionType.Quote: return ExpressionLambdaToSql((exp as UnaryExpression)?.Operand, tsc); - case ExpressionType.Lambda: return ExpressionLambdaToSql((exp as LambdaExpression)?.Body, tsc); - case ExpressionType.TypeAs: - case ExpressionType.Convert: - //var othercExp = ExpressionLambdaToSqlOther(exp, tsc); - //if (string.IsNullOrEmpty(othercExp) == false) return othercExp; - return ExpressionLambdaToSql((exp as UnaryExpression)?.Operand, tsc); - case ExpressionType.Negate: - case ExpressionType.NegateChecked: return "-" + ExpressionLambdaToSql((exp as UnaryExpression)?.Operand, tsc); - case ExpressionType.Constant: return formatSql((exp as ConstantExpression)?.Value, tsc.mapType); - case ExpressionType.Conditional: - var condExp = exp as ConditionalExpression; - return $"case when {ExpressionLambdaToSql(condExp.Test, tsc)} then {ExpressionLambdaToSql(condExp.IfTrue, tsc)} else {ExpressionLambdaToSql(condExp.IfFalse, tsc)} end"; - case ExpressionType.Call: - var exp3 = exp as MethodCallExpression; - var callType = exp3.Object?.Type ?? exp3.Method.DeclaringType; - switch (callType.FullName) { - case "System.String": return ExpressionLambdaToSqlCallString(exp3, tsc); - case "System.Math": return ExpressionLambdaToSqlCallMath(exp3, tsc); - case "System.DateTime": return ExpressionLambdaToSqlCallDateTime(exp3, tsc); - case "System.TimeSpan": return ExpressionLambdaToSqlCallTimeSpan(exp3, tsc); - case "System.Convert": return ExpressionLambdaToSqlCallConvert(exp3, tsc); - } - if (exp3.Method.Name == "Equals" && exp3.Object != null && exp3.Arguments.Count > 0) - return ExpressionBinary("=", exp3.Object, exp3.Arguments[0], tsc); - if (callType.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) { - //if (exp3.Type == typeof(string) && exp3.Arguments.Any() && exp3.Arguments[0].NodeType == ExpressionType.Constant) { - // switch (exp3.Method.Name) { - // case "Sum": return $"sum({(exp3.Arguments[0] as ConstantExpression)?.Value})"; - // case "Avg": return $"avg({(exp3.Arguments[0] as ConstantExpression)?.Value})"; - // case "Max": return $"max({(exp3.Arguments[0] as ConstantExpression)?.Value})"; - // case "Min": return $"min({(exp3.Arguments[0] as ConstantExpression)?.Value})"; - // } - //} - switch (exp3.Method.Name) { - case "Count": return "count(1)"; - case "Sum": return $"sum({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})"; - case "Avg": return $"avg({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})"; - case "Max": return $"max({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})"; - case "Min": return $"min({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})"; - } - } - if (callType.FullName.StartsWith("FreeSql.ISelect`")) { //子表查询 - if (exp3.Method.Name == "Any") { //exists - var anyArgs = exp3.Arguments; - var exp3Stack = new Stack(); - var exp3tmp = exp3.Object; - if (exp3tmp != null && anyArgs.Any()) - exp3Stack.Push(Expression.Call(exp3tmp, callType.GetMethod("Where", anyArgs.Select(a => a.Type).ToArray()), anyArgs.ToArray())); - while (exp3tmp != null) { - exp3Stack.Push(exp3tmp); - switch (exp3tmp.NodeType) { - case ExpressionType.Call: - var exp3tmpCall = (exp3tmp as MethodCallExpression); - exp3tmp = exp3tmpCall.Object == null ? exp3tmpCall.Arguments.FirstOrDefault() : exp3tmpCall.Object; - continue; - case ExpressionType.MemberAccess: exp3tmp = (exp3tmp as MemberExpression).Expression; continue; - } - break; - } - object fsql = null; - List fsqltables = null; - var fsqltable1SetAlias = false; - Type fsqlType = null; - Stack asSelectBefores = new Stack(); - var asSelectSql = ""; - Type asSelectEntityType = null; - MemberExpression asSelectParentExp1 = null; - Expression asSelectParentExp = null; - while (exp3Stack.Any()) { - exp3tmp = exp3Stack.Pop(); - if (exp3tmp.Type.FullName.StartsWith("FreeSql.ISelect`") && fsql == null) { - if (exp3tmp.NodeType == ExpressionType.Call) { - var exp3tmpCall = (exp3tmp as MethodCallExpression); - if (exp3tmpCall.Method.Name == "AsSelect" && exp3tmpCall.Object == null) { - var exp3tmpArg1Type = exp3tmpCall.Arguments.FirstOrDefault()?.Type; - if (exp3tmpArg1Type != null) { - asSelectEntityType = exp3tmpArg1Type.GetElementType() ?? exp3tmpArg1Type.GenericTypeArguments.FirstOrDefault(); - if (asSelectEntityType != null) { - fsql = _dicExpressionLambdaToSqlAsSelectMethodInfo.GetOrAdd(asSelectEntityType, asSelectEntityType2 => typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(asSelectEntityType2)) - .Invoke(_common._orm, null); + if (left == "NULL") + { + var tmp = right; + right = left; + left = tmp; + } + if (right == "NULL") oper = oper == "=" ? " IS " : " IS NOT "; + if (oper == "%") return _common.Mod(left, right, leftExp.Type, rightExp.Type); + tsc.mapType = null; + return $"{left} {oper} {right}"; + } + public string ExpressionLambdaToSql(Expression exp, ExpTSC tsc) + { + if (exp == null) return ""; + if (tsc.isDisableDiyParse == false && _common._orm.Aop.ParseExpression != null) + { + var args = new Aop.ParseExpressionEventArgs(exp, ukexp => ExpressionLambdaToSql(ukexp, tsc.CloneDisableDiyParse())); + _common._orm.Aop.ParseExpression?.Invoke(this, args); + if (string.IsNullOrEmpty(args.Result) == false) return args.Result; + } + switch (exp.NodeType) + { + case ExpressionType.Not: + var notExp = (exp as UnaryExpression)?.Operand; + if (notExp.NodeType == ExpressionType.MemberAccess) + { + var notBody = ExpressionLambdaToSql(notExp, tsc); + if (notBody.Contains(" IS NULL")) return notBody.Replace(" IS NULL", " IS NOT NULL"); + if (notBody.Contains(" IS NOT NULL")) return notBody.Replace(" IS NOT NULL", " IS NULL"); + if (notBody.Contains("=")) return notBody.Replace("=", "!="); + if (notBody.Contains("!=")) return notBody.Replace("!=", "="); + return $"{notBody} = {formatSql(false, null)}"; + } + return $"not({ExpressionLambdaToSql(notExp, tsc)})"; + case ExpressionType.Quote: return ExpressionLambdaToSql((exp as UnaryExpression)?.Operand, tsc); + case ExpressionType.Lambda: return ExpressionLambdaToSql((exp as LambdaExpression)?.Body, tsc); + case ExpressionType.TypeAs: + case ExpressionType.Convert: + //var othercExp = ExpressionLambdaToSqlOther(exp, tsc); + //if (string.IsNullOrEmpty(othercExp) == false) return othercExp; + return ExpressionLambdaToSql((exp as UnaryExpression)?.Operand, tsc); + case ExpressionType.Negate: + case ExpressionType.NegateChecked: return "-" + ExpressionLambdaToSql((exp as UnaryExpression)?.Operand, tsc); + case ExpressionType.Constant: return formatSql((exp as ConstantExpression)?.Value, tsc.mapType); + case ExpressionType.Conditional: + var condExp = exp as ConditionalExpression; + return $"case when {ExpressionLambdaToSql(condExp.Test, tsc)} then {ExpressionLambdaToSql(condExp.IfTrue, tsc)} else {ExpressionLambdaToSql(condExp.IfFalse, tsc)} end"; + case ExpressionType.Call: + var exp3 = exp as MethodCallExpression; + var callType = exp3.Object?.Type ?? exp3.Method.DeclaringType; + switch (callType.FullName) + { + case "System.String": return ExpressionLambdaToSqlCallString(exp3, tsc); + case "System.Math": return ExpressionLambdaToSqlCallMath(exp3, tsc); + case "System.DateTime": return ExpressionLambdaToSqlCallDateTime(exp3, tsc); + case "System.TimeSpan": return ExpressionLambdaToSqlCallTimeSpan(exp3, tsc); + case "System.Convert": return ExpressionLambdaToSqlCallConvert(exp3, tsc); + } + if (exp3.Method.Name == "Equals" && exp3.Object != null && exp3.Arguments.Count > 0) + return ExpressionBinary("=", exp3.Object, exp3.Arguments[0], tsc); + if (callType.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) + { + //if (exp3.Type == typeof(string) && exp3.Arguments.Any() && exp3.Arguments[0].NodeType == ExpressionType.Constant) { + // switch (exp3.Method.Name) { + // case "Sum": return $"sum({(exp3.Arguments[0] as ConstantExpression)?.Value})"; + // case "Avg": return $"avg({(exp3.Arguments[0] as ConstantExpression)?.Value})"; + // case "Max": return $"max({(exp3.Arguments[0] as ConstantExpression)?.Value})"; + // case "Min": return $"min({(exp3.Arguments[0] as ConstantExpression)?.Value})"; + // } + //} + switch (exp3.Method.Name) + { + case "Count": return "count(1)"; + case "Sum": return $"sum({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})"; + case "Avg": return $"avg({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})"; + case "Max": return $"max({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})"; + case "Min": return $"min({ExpressionLambdaToSql(exp3.Arguments[0], tsc)})"; + } + } + if (callType.FullName.StartsWith("FreeSql.ISelect`")) + { //子表查询 + if (exp3.Method.Name == "Any") + { //exists + var anyArgs = exp3.Arguments; + var exp3Stack = new Stack(); + var exp3tmp = exp3.Object; + if (exp3tmp != null && anyArgs.Any()) + exp3Stack.Push(Expression.Call(exp3tmp, callType.GetMethod("Where", anyArgs.Select(a => a.Type).ToArray()), anyArgs.ToArray())); + while (exp3tmp != null) + { + exp3Stack.Push(exp3tmp); + switch (exp3tmp.NodeType) + { + case ExpressionType.Call: + var exp3tmpCall = (exp3tmp as MethodCallExpression); + exp3tmp = exp3tmpCall.Object == null ? exp3tmpCall.Arguments.FirstOrDefault() : exp3tmpCall.Object; + continue; + case ExpressionType.MemberAccess: exp3tmp = (exp3tmp as MemberExpression).Expression; continue; + } + break; + } + object fsql = null; + List fsqltables = null; + var fsqltable1SetAlias = false; + Type fsqlType = null; + Stack asSelectBefores = new Stack(); + var asSelectSql = ""; + Type asSelectEntityType = null; + MemberExpression asSelectParentExp1 = null; + Expression asSelectParentExp = null; + while (exp3Stack.Any()) + { + exp3tmp = exp3Stack.Pop(); + if (exp3tmp.Type.FullName.StartsWith("FreeSql.ISelect`") && fsql == null) + { + if (exp3tmp.NodeType == ExpressionType.Call) + { + var exp3tmpCall = (exp3tmp as MethodCallExpression); + if (exp3tmpCall.Method.Name == "AsSelect" && exp3tmpCall.Object == null) + { + var exp3tmpArg1Type = exp3tmpCall.Arguments.FirstOrDefault()?.Type; + if (exp3tmpArg1Type != null) + { + asSelectEntityType = exp3tmpArg1Type.GetElementType() ?? exp3tmpArg1Type.GenericTypeArguments.FirstOrDefault(); + if (asSelectEntityType != null) + { + fsql = _dicExpressionLambdaToSqlAsSelectMethodInfo.GetOrAdd(asSelectEntityType, asSelectEntityType2 => typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(asSelectEntityType2)) + .Invoke(_common._orm, null); - if (asSelectBefores.Any()) { - asSelectParentExp1 = asSelectBefores.Pop() as MemberExpression; - if (asSelectBefores.Any()) { - asSelectParentExp = asSelectBefores.Pop(); - if (asSelectParentExp != null) { - var testExecuteExp = asSelectParentExp; - if (asSelectParentExp.NodeType == ExpressionType.Parameter) //执行leftjoin关联 - testExecuteExp = Expression.Property(testExecuteExp, _common.GetTableByEntity(asSelectParentExp.Type).ColumnsByCs.First().Key); - var tsc2 = tsc.CloneSetgetSelectGroupingMapStringAndgetSelectGroupingMapStringAndtbtype(new List(), tsc.getSelectGroupingMapString, SelectTableInfoType.LeftJoin); - tsc2.isDisableDiyParse = true; - tsc2.style = ExpressionStyle.AsSelect; - asSelectSql = ExpressionLambdaToSql(testExecuteExp, tsc2); - } - } - } - } - } - } - } - if (fsql == null) fsql = Expression.Lambda(exp3tmp).Compile().DynamicInvoke(); - fsqlType = fsql?.GetType(); - if (fsqlType == null) break; - fsqlType.GetField("_limit", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(fsql, 1); - fsqltables = fsqlType.GetField("_tables", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(fsql) as List; - //fsqltables[0].Alias = $"{tsc._tables[0].Alias}_{fsqltables[0].Alias}"; - fsqltables.AddRange(tsc._tables.Select(a => new SelectTableInfo { - Alias = a.Alias, - On = "1=1", - Table = a.Table, - Type = SelectTableInfoType.Parent, - Parameter = a.Parameter - })); - } else if (fsqlType != null) { - var call3Exp = exp3tmp as MethodCallExpression; - var method = fsqlType.GetMethod(call3Exp.Method.Name, call3Exp.Arguments.Select(a => a.Type).ToArray()); - if (call3Exp.Method.ContainsGenericParameters) method.MakeGenericMethod(call3Exp.Method.GetGenericArguments()); - var parms = method.GetParameters(); - var args = new object[call3Exp.Arguments.Count]; - for (var a = 0; a < args.Length; a++) { - var arg3Exp = call3Exp.Arguments[a]; - if (arg3Exp.NodeType == ExpressionType.Constant) { - args[a] = (arg3Exp as ConstantExpression)?.Value; - } else { - var argExp = (arg3Exp as UnaryExpression)?.Operand; - if (argExp != null && argExp.NodeType == ExpressionType.Lambda) { - if (fsqltable1SetAlias == false) { - fsqltables[0].Alias = (argExp as LambdaExpression).Parameters.First().Name; - fsqltable1SetAlias = true; - } - } - args[a] = argExp ?? Expression.Lambda(arg3Exp).Compile().DynamicInvoke(); - //if (args[a] == null) ExpressionLambdaToSql(call3Exp.Arguments[a], fsqltables, null, null, SelectTableInfoType.From, true); - } - } - method.Invoke(fsql, args); - } - if (fsql == null) asSelectBefores.Push(exp3tmp); - } - if (fsql != null) { - if (asSelectParentExp != null) { //执行 asSelect() 的关联,OneToMany,ManyToMany - if (fsqltables[0].Parameter == null) { - fsqltables[0].Alias = $"tb_{fsqltables.Count}"; - fsqltables[0].Parameter = Expression.Parameter(asSelectEntityType, fsqltables[0].Alias); - } - var fsqlWhere = _dicExpressionLambdaToSqlAsSelectWhereMethodInfo.GetOrAdd(asSelectEntityType, asSelectEntityType3 => - typeof(ISelect<>).MakeGenericType(asSelectEntityType3).GetMethod("Where", new[] { - typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(asSelectEntityType3, typeof(bool))) - })); - var parm123Tb = _common.GetTableByEntity(asSelectParentExp.Type); - var parm123Ref = parm123Tb.GetTableRef(asSelectParentExp1.Member.Name, true); - var fsqlWhereParam = fsqltables.First().Parameter; //Expression.Parameter(asSelectEntityType); - Expression fsqlWhereExp = null; - if (parm123Ref.RefType == TableRefType.ManyToMany) { - //g.mysql.Select().Where(a => g.mysql.Select().Where(b => b.Tag_id == a.Id && b.Song_id == 1).Any()); - var manyTb = _common.GetTableByEntity(parm123Ref.RefMiddleEntityType); - var manySubSelectWhere = _dicExpressionLambdaToSqlAsSelectWhereMethodInfo.GetOrAdd(parm123Ref.RefMiddleEntityType, refMiddleEntityType3 => - typeof(ISelect<>).MakeGenericType(refMiddleEntityType3).GetMethod("Where", new[] { - typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(refMiddleEntityType3, typeof(bool))) - })); - var manySubSelectWhereSql = _dicExpressionLambdaToSqlAsSelectWhereSqlMethodInfo.GetOrAdd(parm123Ref.RefMiddleEntityType, refMiddleEntityType3 => - typeof(ISelect0<,>).MakeGenericType(typeof(ISelect<>).MakeGenericType(refMiddleEntityType3), refMiddleEntityType3).GetMethod("Where", new[] { typeof(string), typeof(object) })); - var manySubSelectAny = _dicExpressionLambdaToSqlAsSelectAnyMethodInfo.GetOrAdd(parm123Ref.RefMiddleEntityType, refMiddleEntityType3 => - typeof(ISelect0<,>).MakeGenericType(typeof(ISelect<>).MakeGenericType(refMiddleEntityType3), refMiddleEntityType3).GetMethod("Any", new Type[0])); - var manySubSelectAsSelectExp = _dicFreeSqlGlobalExtensionsAsSelectExpression.GetOrAdd(parm123Ref.RefMiddleEntityType, refMiddleEntityType3 => - Expression.Call( - typeof(FreeSqlGlobalExtensions).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(mfil => mfil.Name == "AsSelect" && mfil.GetParameters().Length == 1).FirstOrDefault()?.MakeGenericMethod(refMiddleEntityType3), - Expression.Constant(Activator.CreateInstance(typeof(List<>).MakeGenericType(refMiddleEntityType3))) - )); - var manyMainParam = tsc._tables[0].Parameter; - var manySubSelectWhereParam = Expression.Parameter(parm123Ref.RefMiddleEntityType, $"M{fsqlWhereParam.Name}_M{asSelectParentExp.ToString().Replace(".", "__")}");//, $"{fsqlWhereParam.Name}__"); - Expression manySubSelectWhereExp = null; - for (var mn = 0; mn < parm123Ref.Columns.Count; mn++) { - var col1 = parm123Ref.MiddleColumns[mn]; - var col2 = parm123Ref.Columns[mn]; - var pexp1 = Expression.Property(manySubSelectWhereParam, col1.CsName); - var pexp2 = Expression.Property(asSelectParentExp, col2.CsName); - if (col1.CsType != col2.CsType) { - if (col1.CsType.IsNullableType()) pexp1 = Expression.Property(pexp1, _dicNullableValueProperty.GetOrAdd(col1.CsType, ct1 => ct1.GetProperty("Value"))); - if (col2.CsType.IsNullableType()) pexp2 = Expression.Property(pexp2, _dicNullableValueProperty.GetOrAdd(col2.CsType, ct2 => ct2.GetProperty("Value"))); - } - var tmpExp = Expression.Equal(pexp1, pexp2); - if (mn == 0) manySubSelectWhereExp = tmpExp; - else manySubSelectWhereExp = Expression.AndAlso(manySubSelectWhereExp, tmpExp); - } - var manySubSelectExpBoy = Expression.Call( - manySubSelectAsSelectExp, - manySubSelectWhere, - Expression.Lambda( - manySubSelectWhereExp, - manySubSelectWhereParam - ) - ); - Expression fsqlManyWhereExp = null; - for (var mn = 0; mn < parm123Ref.RefColumns.Count; mn++) { - var col1 = parm123Ref.RefColumns[mn]; - var col2 = parm123Ref.MiddleColumns[mn + parm123Ref.Columns.Count + mn]; - var pexp1 = Expression.Property(fsqlWhereParam, col1.CsName); - var pexp2 = Expression.Property(manySubSelectWhereParam, col2.CsName); - if (col1.CsType != col2.CsType) { - if (col1.CsType.IsNullableType()) pexp1 = Expression.Property(pexp1, _dicNullableValueProperty.GetOrAdd(col1.CsType, ct1 => ct1.GetProperty("Value"))); - if (col2.CsType.IsNullableType()) pexp2 = Expression.Property(pexp2, _dicNullableValueProperty.GetOrAdd(col2.CsType, ct2 => ct2.GetProperty("Value"))); - } - var tmpExp = Expression.Equal(pexp1, pexp2); - if (mn == 0) fsqlManyWhereExp = tmpExp; - else fsqlManyWhereExp = Expression.AndAlso(fsqlManyWhereExp, tmpExp); - } - fsqltables.Add(new SelectTableInfo { Alias = manySubSelectWhereParam.Name, Parameter = manySubSelectWhereParam, Table = manyTb, Type = SelectTableInfoType.Parent }); - fsqlWhere.Invoke(fsql, new object[] { Expression.Lambda(fsqlManyWhereExp, fsqlWhereParam) }); - var sql2 = fsqlType.GetMethod("ToSql", new Type[] { typeof(string) })?.Invoke(fsql, new object[] { "1" })?.ToString(); - if (string.IsNullOrEmpty(sql2) == false) - manySubSelectExpBoy = Expression.Call(manySubSelectExpBoy, manySubSelectWhereSql, Expression.Constant($"exists({sql2.Replace("\r\n", "\r\n\t")})"), Expression.Constant(null)); - manySubSelectExpBoy = Expression.Call(manySubSelectExpBoy, manySubSelectAny); - asSelectBefores.Clear(); + if (asSelectBefores.Any()) + { + asSelectParentExp1 = asSelectBefores.Pop() as MemberExpression; + if (asSelectBefores.Any()) + { + asSelectParentExp = asSelectBefores.Pop(); + if (asSelectParentExp != null) + { + var testExecuteExp = asSelectParentExp; + if (asSelectParentExp.NodeType == ExpressionType.Parameter) //执行leftjoin关联 + testExecuteExp = Expression.Property(testExecuteExp, _common.GetTableByEntity(asSelectParentExp.Type).ColumnsByCs.First().Key); + var tsc2 = tsc.CloneSetgetSelectGroupingMapStringAndgetSelectGroupingMapStringAndtbtype(new List(), tsc.getSelectGroupingMapString, SelectTableInfoType.LeftJoin); + tsc2.isDisableDiyParse = true; + tsc2.style = ExpressionStyle.AsSelect; + asSelectSql = ExpressionLambdaToSql(testExecuteExp, tsc2); + } + } + } + } + } + } + } + if (fsql == null) fsql = Expression.Lambda(exp3tmp).Compile().DynamicInvoke(); + fsqlType = fsql?.GetType(); + if (fsqlType == null) break; + fsqlType.GetField("_limit", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(fsql, 1); + fsqltables = fsqlType.GetField("_tables", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(fsql) as List; + //fsqltables[0].Alias = $"{tsc._tables[0].Alias}_{fsqltables[0].Alias}"; + fsqltables.AddRange(tsc._tables.Select(a => new SelectTableInfo + { + Alias = a.Alias, + On = "1=1", + Table = a.Table, + Type = SelectTableInfoType.Parent, + Parameter = a.Parameter + })); + } + else if (fsqlType != null) + { + var call3Exp = exp3tmp as MethodCallExpression; + var method = fsqlType.GetMethod(call3Exp.Method.Name, call3Exp.Arguments.Select(a => a.Type).ToArray()); + if (call3Exp.Method.ContainsGenericParameters) method.MakeGenericMethod(call3Exp.Method.GetGenericArguments()); + var parms = method.GetParameters(); + var args = new object[call3Exp.Arguments.Count]; + for (var a = 0; a < args.Length; a++) + { + var arg3Exp = call3Exp.Arguments[a]; + if (arg3Exp.NodeType == ExpressionType.Constant) + { + args[a] = (arg3Exp as ConstantExpression)?.Value; + } + else + { + var argExp = (arg3Exp as UnaryExpression)?.Operand; + if (argExp != null && argExp.NodeType == ExpressionType.Lambda) + { + if (fsqltable1SetAlias == false) + { + fsqltables[0].Alias = (argExp as LambdaExpression).Parameters.First().Name; + fsqltable1SetAlias = true; + } + } + args[a] = argExp ?? Expression.Lambda(arg3Exp).Compile().DynamicInvoke(); + //if (args[a] == null) ExpressionLambdaToSql(call3Exp.Arguments[a], fsqltables, null, null, SelectTableInfoType.From, true); + } + } + method.Invoke(fsql, args); + } + if (fsql == null) asSelectBefores.Push(exp3tmp); + } + if (fsql != null) + { + if (asSelectParentExp != null) + { //执行 asSelect() 的关联,OneToMany,ManyToMany + if (fsqltables[0].Parameter == null) + { + fsqltables[0].Alias = $"tb_{fsqltables.Count}"; + fsqltables[0].Parameter = Expression.Parameter(asSelectEntityType, fsqltables[0].Alias); + } + var fsqlWhere = _dicExpressionLambdaToSqlAsSelectWhereMethodInfo.GetOrAdd(asSelectEntityType, asSelectEntityType3 => + typeof(ISelect<>).MakeGenericType(asSelectEntityType3).GetMethod("Where", new[] { + typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(asSelectEntityType3, typeof(bool))) + })); + var parm123Tb = _common.GetTableByEntity(asSelectParentExp.Type); + var parm123Ref = parm123Tb.GetTableRef(asSelectParentExp1.Member.Name, true); + var fsqlWhereParam = fsqltables.First().Parameter; //Expression.Parameter(asSelectEntityType); + Expression fsqlWhereExp = null; + if (parm123Ref.RefType == TableRefType.ManyToMany) + { + //g.mysql.Select().Where(a => g.mysql.Select().Where(b => b.Tag_id == a.Id && b.Song_id == 1).Any()); + var manyTb = _common.GetTableByEntity(parm123Ref.RefMiddleEntityType); + var manySubSelectWhere = _dicExpressionLambdaToSqlAsSelectWhereMethodInfo.GetOrAdd(parm123Ref.RefMiddleEntityType, refMiddleEntityType3 => + typeof(ISelect<>).MakeGenericType(refMiddleEntityType3).GetMethod("Where", new[] { + typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(refMiddleEntityType3, typeof(bool))) + })); + var manySubSelectWhereSql = _dicExpressionLambdaToSqlAsSelectWhereSqlMethodInfo.GetOrAdd(parm123Ref.RefMiddleEntityType, refMiddleEntityType3 => + typeof(ISelect0<,>).MakeGenericType(typeof(ISelect<>).MakeGenericType(refMiddleEntityType3), refMiddleEntityType3).GetMethod("Where", new[] { typeof(string), typeof(object) })); + var manySubSelectAny = _dicExpressionLambdaToSqlAsSelectAnyMethodInfo.GetOrAdd(parm123Ref.RefMiddleEntityType, refMiddleEntityType3 => + typeof(ISelect0<,>).MakeGenericType(typeof(ISelect<>).MakeGenericType(refMiddleEntityType3), refMiddleEntityType3).GetMethod("Any", new Type[0])); + var manySubSelectAsSelectExp = _dicFreeSqlGlobalExtensionsAsSelectExpression.GetOrAdd(parm123Ref.RefMiddleEntityType, refMiddleEntityType3 => + Expression.Call( + typeof(FreeSqlGlobalExtensions).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(mfil => mfil.Name == "AsSelect" && mfil.GetParameters().Length == 1).FirstOrDefault()?.MakeGenericMethod(refMiddleEntityType3), + Expression.Constant(Activator.CreateInstance(typeof(List<>).MakeGenericType(refMiddleEntityType3))) + )); + var manyMainParam = tsc._tables[0].Parameter; + var manySubSelectWhereParam = Expression.Parameter(parm123Ref.RefMiddleEntityType, $"M{fsqlWhereParam.Name}_M{asSelectParentExp.ToString().Replace(".", "__")}");//, $"{fsqlWhereParam.Name}__"); + Expression manySubSelectWhereExp = null; + for (var mn = 0; mn < parm123Ref.Columns.Count; mn++) + { + var col1 = parm123Ref.MiddleColumns[mn]; + var col2 = parm123Ref.Columns[mn]; + var pexp1 = Expression.Property(manySubSelectWhereParam, col1.CsName); + var pexp2 = Expression.Property(asSelectParentExp, col2.CsName); + if (col1.CsType != col2.CsType) + { + if (col1.CsType.IsNullableType()) pexp1 = Expression.Property(pexp1, _dicNullableValueProperty.GetOrAdd(col1.CsType, ct1 => ct1.GetProperty("Value"))); + if (col2.CsType.IsNullableType()) pexp2 = Expression.Property(pexp2, _dicNullableValueProperty.GetOrAdd(col2.CsType, ct2 => ct2.GetProperty("Value"))); + } + var tmpExp = Expression.Equal(pexp1, pexp2); + if (mn == 0) manySubSelectWhereExp = tmpExp; + else manySubSelectWhereExp = Expression.AndAlso(manySubSelectWhereExp, tmpExp); + } + var manySubSelectExpBoy = Expression.Call( + manySubSelectAsSelectExp, + manySubSelectWhere, + Expression.Lambda( + manySubSelectWhereExp, + manySubSelectWhereParam + ) + ); + Expression fsqlManyWhereExp = null; + for (var mn = 0; mn < parm123Ref.RefColumns.Count; mn++) + { + var col1 = parm123Ref.RefColumns[mn]; + var col2 = parm123Ref.MiddleColumns[mn + parm123Ref.Columns.Count + mn]; + var pexp1 = Expression.Property(fsqlWhereParam, col1.CsName); + var pexp2 = Expression.Property(manySubSelectWhereParam, col2.CsName); + if (col1.CsType != col2.CsType) + { + if (col1.CsType.IsNullableType()) pexp1 = Expression.Property(pexp1, _dicNullableValueProperty.GetOrAdd(col1.CsType, ct1 => ct1.GetProperty("Value"))); + if (col2.CsType.IsNullableType()) pexp2 = Expression.Property(pexp2, _dicNullableValueProperty.GetOrAdd(col2.CsType, ct2 => ct2.GetProperty("Value"))); + } + var tmpExp = Expression.Equal(pexp1, pexp2); + if (mn == 0) fsqlManyWhereExp = tmpExp; + else fsqlManyWhereExp = Expression.AndAlso(fsqlManyWhereExp, tmpExp); + } + fsqltables.Add(new SelectTableInfo { Alias = manySubSelectWhereParam.Name, Parameter = manySubSelectWhereParam, Table = manyTb, Type = SelectTableInfoType.Parent }); + fsqlWhere.Invoke(fsql, new object[] { Expression.Lambda(fsqlManyWhereExp, fsqlWhereParam) }); + var sql2 = fsqlType.GetMethod("ToSql", new Type[] { typeof(string) })?.Invoke(fsql, new object[] { "1" })?.ToString(); + if (string.IsNullOrEmpty(sql2) == false) + manySubSelectExpBoy = Expression.Call(manySubSelectExpBoy, manySubSelectWhereSql, Expression.Constant($"exists({sql2.Replace("\r\n", "\r\n\t")})"), Expression.Constant(null)); + manySubSelectExpBoy = Expression.Call(manySubSelectExpBoy, manySubSelectAny); + asSelectBefores.Clear(); - return ExpressionLambdaToSql(manySubSelectExpBoy, tsc); - } - for (var mn = 0; mn < parm123Ref.Columns.Count; mn++) { - var col1 = parm123Ref.RefColumns[mn]; - var col2 = parm123Ref.Columns[mn]; - var pexp1 = Expression.Property(fsqlWhereParam, col1.CsName); - var pexp2 = Expression.Property(asSelectParentExp, col2.CsName); - if (col1.CsType != col2.CsType) { - if (col1.CsType.IsNullableType()) pexp1 = Expression.Property(pexp1, _dicNullableValueProperty.GetOrAdd(col1.CsType, ct1 => ct1.GetProperty("Value"))); - if (col2.CsType.IsNullableType()) pexp2 = Expression.Property(pexp2, _dicNullableValueProperty.GetOrAdd(col2.CsType, ct2 => ct2.GetProperty("Value"))); - } - var tmpExp = Expression.Equal(pexp1, pexp2); - if (mn == 0) fsqlWhereExp = tmpExp; - else fsqlWhereExp = Expression.AndAlso(fsqlWhereExp, tmpExp); - } - fsqlWhere.Invoke(fsql, new object[] { Expression.Lambda(fsqlWhereExp, fsqlWhereParam) }); - } - asSelectBefores.Clear(); - var sql = fsqlType.GetMethod("ToSql", new Type[] { typeof(string) })?.Invoke(fsql, new object[] { "1" })?.ToString(); - if (string.IsNullOrEmpty(sql) == false) - return $"exists({sql.Replace("\r\n", "\r\n\t")})"; - } - asSelectBefores.Clear(); - } - } - //var eleType = callType.GetElementType() ?? callType.GenericTypeArguments.FirstOrDefault(); - //if (eleType != null && typeof(IEnumerable<>).MakeGenericType(eleType).IsAssignableFrom(callType)) { //集合导航属性子查询 - // if (exp3.Method.Name == "Any") { //exists - - // } - //} - var other3Exp = ExpressionLambdaToSqlOther(exp3, tsc); - if (string.IsNullOrEmpty(other3Exp) == false) return other3Exp; - throw new Exception($"未实现函数表达式 {exp3} 解析"); - case ExpressionType.Parameter: - case ExpressionType.MemberAccess: - var exp4 = exp as MemberExpression; - if (exp4 != null) { - if (exp4.Expression != null && exp4.Expression.Type.IsArray == false && exp4.Expression.Type.IsNullableType()) - return exp4.Member.Name == "HasValue" ? $"{ExpressionLambdaToSql(exp4.Expression, tsc)} IS NOT NULL" : ExpressionLambdaToSql(exp4.Expression, tsc); - var extRet = ""; - var memberType = exp4.Expression?.Type ?? exp4.Type; - switch (memberType.FullName) { - case "System.String": extRet = ExpressionLambdaToSqlMemberAccessString(exp4, tsc); break; - case "System.DateTime": extRet = ExpressionLambdaToSqlMemberAccessDateTime(exp4, tsc); break; - case "System.TimeSpan": extRet = ExpressionLambdaToSqlMemberAccessTimeSpan(exp4, tsc); break; - } - if (string.IsNullOrEmpty(extRet) == false) return extRet; - var other4Exp = ExpressionLambdaToSqlOther(exp4, tsc); - if (string.IsNullOrEmpty(other4Exp) == false) return other4Exp; - } - var expStack = new Stack(); - expStack.Push(exp); - MethodCallExpression callExp = null; - var exp2 = exp4?.Expression; - while (true) { - switch(exp2?.NodeType) { - case ExpressionType.Constant: - expStack.Push(exp2); - break; - case ExpressionType.Parameter: - expStack.Push(exp2); - break; - case ExpressionType.MemberAccess: - expStack.Push(exp2); - exp2 = (exp2 as MemberExpression).Expression; - if (exp2 == null) break; - continue; - case ExpressionType.Call: - callExp = exp2 as MethodCallExpression; - expStack.Push(exp2); - exp2 = callExp.Object; - if (exp2 == null) break; - continue; - case ExpressionType.TypeAs: - case ExpressionType.Convert: - var oper2 = (exp2 as UnaryExpression).Operand; - if (oper2.NodeType == ExpressionType.Parameter) { - var oper2Parm = oper2 as ParameterExpression; - expStack.Push(Expression.Parameter(exp2.Type, oper2Parm.Name)); - } else - expStack.Push(oper2); - break; - } - break; - } - if (expStack.First().NodeType != ExpressionType.Parameter) return formatSql(Expression.Lambda(exp).Compile().DynamicInvoke(), tsc.mapType); - if (callExp != null) return ExpressionLambdaToSql(callExp, tsc); - if (tsc.getSelectGroupingMapString != null && expStack.First().Type.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) { - if (tsc.getSelectGroupingMapString != null) { - var expText = tsc.getSelectGroupingMapString(expStack.Where((a, b) => b >= 2).ToArray()); - if (string.IsNullOrEmpty(expText) == false) return expText; - } - } + return ExpressionLambdaToSql(manySubSelectExpBoy, tsc); + } + for (var mn = 0; mn < parm123Ref.Columns.Count; mn++) + { + var col1 = parm123Ref.RefColumns[mn]; + var col2 = parm123Ref.Columns[mn]; + var pexp1 = Expression.Property(fsqlWhereParam, col1.CsName); + var pexp2 = Expression.Property(asSelectParentExp, col2.CsName); + if (col1.CsType != col2.CsType) + { + if (col1.CsType.IsNullableType()) pexp1 = Expression.Property(pexp1, _dicNullableValueProperty.GetOrAdd(col1.CsType, ct1 => ct1.GetProperty("Value"))); + if (col2.CsType.IsNullableType()) pexp2 = Expression.Property(pexp2, _dicNullableValueProperty.GetOrAdd(col2.CsType, ct2 => ct2.GetProperty("Value"))); + } + var tmpExp = Expression.Equal(pexp1, pexp2); + if (mn == 0) fsqlWhereExp = tmpExp; + else fsqlWhereExp = Expression.AndAlso(fsqlWhereExp, tmpExp); + } + fsqlWhere.Invoke(fsql, new object[] { Expression.Lambda(fsqlWhereExp, fsqlWhereParam) }); + } + asSelectBefores.Clear(); + var sql = fsqlType.GetMethod("ToSql", new Type[] { typeof(string) })?.Invoke(fsql, new object[] { "1" })?.ToString(); + if (string.IsNullOrEmpty(sql) == false) + return $"exists({sql.Replace("\r\n", "\r\n\t")})"; + } + asSelectBefores.Clear(); + } + } + //var eleType = callType.GetElementType() ?? callType.GenericTypeArguments.FirstOrDefault(); + //if (eleType != null && typeof(IEnumerable<>).MakeGenericType(eleType).IsAssignableFrom(callType)) { //集合导航属性子查询 + // if (exp3.Method.Name == "Any") { //exists - if (tsc._tables == null) { - var pp = expStack.Pop() as ParameterExpression; - var memberExp = expStack.Pop() as MemberExpression; - var tb = _common.GetTableByEntity(pp.Type); - if (tb.ColumnsByCs.ContainsKey(memberExp.Member.Name) == false) throw new ArgumentException($"{tb.DbName} 找不到列 {memberExp.Member.Name}"); - if (tsc._selectColumnMap != null) { - tsc._selectColumnMap.Add(new SelectColumnInfo { Table = null, Column = tb.ColumnsByCs[memberExp.Member.Name] }); - } - var name = tb.ColumnsByCs[memberExp.Member.Name].Attribute.Name; - if (tsc.isQuoteName) name = _common.QuoteSqlName(name); - return name; - } - Func getOrAddTable = (tbtmp, alias, isa, parmExp, mp) => { - var finds = new SelectTableInfo[0]; - if (tsc.style == ExpressionStyle.SelectColumns) { - finds = tsc._tables.Where(a => a.Table.Type == tbtmp.Type).ToArray(); - if (finds.Any()) finds = new[] { finds.First() }; - } - if (finds.Length != 1 && isa && parmExp != null) - finds = tsc._tables.Where(a => a.Parameter == parmExp).ToArray(); - if (finds.Length != 1) { - var navdot = string.IsNullOrEmpty(alias) ? new SelectTableInfo[0] : tsc._tables.Where(a2 => a2.Parameter != null && alias.StartsWith($"{a2.Alias}__")).ToArray(); - if (navdot.Length > 0) { - var isthis = navdot[0] == tsc._tables[0]; - finds = tsc._tables.Where(a2 => (isa && a2.Parameter != null || !isa && a2.Parameter == null) && - a2.Table.Type == tbtmp.Type && a2.Alias == alias && a2.Alias.StartsWith($"{navdot[0].Alias}__") && - (isthis && a2.Type != SelectTableInfoType.Parent || !isthis && a2.Type == SelectTableInfoType.Parent)).ToArray(); - if (finds.Length == 0) - finds = tsc._tables.Where(a2 => - a2.Table.Type == tbtmp.Type && a2.Alias == alias && a2.Alias.StartsWith($"{navdot[0].Alias}__") && - (isthis && a2.Type != SelectTableInfoType.Parent || !isthis && a2.Type == SelectTableInfoType.Parent)).ToArray(); - } else { - finds = tsc._tables.Where(a2 => (isa && a2.Parameter != null || isa && a2.Parameter == null) && - a2.Table.Type == tbtmp.Type && a2.Alias == alias).ToArray(); - if (finds.Length != 1) { - finds = tsc._tables.Where(a2 => (isa && a2.Parameter != null || isa && a2.Parameter == null) && - a2.Table.Type == tbtmp.Type).ToArray(); - if (finds.Length != 1) { - finds = tsc._tables.Where(a2 => (isa && a2.Parameter != null || isa && a2.Parameter == null) && - a2.Table.Type == tbtmp.Type).ToArray(); - if (finds.Length != 1) - finds = tsc._tables.Where(a2 => a2.Table.Type == tbtmp.Type).ToArray(); - } - } - } - //finds = tsc._tables.Where((a2, c2) => (isa || a2.Parameter == null) && a2.Table.CsName == tbtmp.CsName && (isthis && a2.Type != SelectTableInfoType.Parent || !isthis)).ToArray(); //外部表,内部表一起查 - //if (finds.Length > 1) { - // finds = tsc._tables.Where((a2, c2) => (isa || a2.Parameter == null) && a2.Table.CsName == tbtmp.CsName && a2.Type == SelectTableInfoType.Parent && a2.Alias == alias).ToArray(); //查询外部表 - // if (finds.Any() == false) { - // finds = tsc._tables.Where((a2, c2) => (isa || a2.Parameter == null) && a2.Table.CsName == tbtmp.CsName && a2.Type != SelectTableInfoType.Parent).ToArray(); //查询内部表 - // if (finds.Length > 1) - // finds = tsc._tables.Where((a2, c2) => (isa || a2.Parameter == null) && a2.Table.CsName == tbtmp.CsName && a2.Type != SelectTableInfoType.Parent && a2.Alias == alias).ToArray(); - // } - //} - } - var find = finds.Length == 1 ? finds.First() : null; - if (find != null && isa && parmExp != null && find.Parameter != parmExp) - find.Parameter = parmExp; - if (find == null) { - tsc._tables.Add(find = new SelectTableInfo { Table = tbtmp, Alias = alias, On = null, Type = mp == null ? tsc.tbtype : SelectTableInfoType.LeftJoin, Parameter = isa ? parmExp : null }); - if (mp?.Expression != null) { //导航条件,OneToOne、ManyToOne - var firstTb = tsc._tables.First().Table; - var parentTb = _common.GetTableByEntity(mp.Expression.Type); - var parentTbRef = parentTb?.GetTableRef(mp.Member.Name, tsc.style == ExpressionStyle.AsSelect); - if (parentTbRef != null) { - Expression navCondExp = null; - for (var mn = 0; mn < parentTbRef.Columns.Count; mn++) { - var col1 = parentTbRef.RefColumns[mn]; - var col2 = parentTbRef.Columns[mn]; - var pexp1 = Expression.Property(mp, col1.CsName); - var pexp2 = Expression.Property(mp.Expression, col2.CsName); - if (col1.CsType != col2.CsType) { - if (col1.CsType.IsNullableType()) pexp1 = Expression.Property(pexp1, _dicNullableValueProperty.GetOrAdd(col1.CsType, ct1 => ct1.GetProperty("Value"))); - if (col2.CsType.IsNullableType()) pexp2 = Expression.Property(pexp2, _dicNullableValueProperty.GetOrAdd(col2.CsType, ct2 => ct2.GetProperty("Value"))); - } - var tmpExp = Expression.Equal(pexp1, pexp2); - if (mn == 0) navCondExp = tmpExp; - else navCondExp = Expression.AndAlso(navCondExp, tmpExp); - } - if (find.Type == SelectTableInfoType.InnerJoin || - find.Type == SelectTableInfoType.LeftJoin || - find.Type == SelectTableInfoType.RightJoin) - find.On = ExpressionLambdaToSql(navCondExp, tsc.CloneSetgetSelectGroupingMapStringAndgetSelectGroupingMapStringAndtbtype(null, null, find.Type)); - else - find.NavigateCondition = ExpressionLambdaToSql(navCondExp, tsc.CloneSetgetSelectGroupingMapStringAndgetSelectGroupingMapStringAndtbtype(null, null, find.Type)); - } - } - } - return find; - }; + // } + //} + var other3Exp = ExpressionLambdaToSqlOther(exp3, tsc); + if (string.IsNullOrEmpty(other3Exp) == false) return other3Exp; + throw new Exception($"未实现函数表达式 {exp3} 解析"); + case ExpressionType.Parameter: + case ExpressionType.MemberAccess: + var exp4 = exp as MemberExpression; + if (exp4 != null) + { + if (exp4.Expression != null && exp4.Expression.Type.IsArray == false && exp4.Expression.Type.IsNullableType()) + return exp4.Member.Name == "HasValue" ? $"{ExpressionLambdaToSql(exp4.Expression, tsc)} IS NOT NULL" : ExpressionLambdaToSql(exp4.Expression, tsc); + var extRet = ""; + var memberType = exp4.Expression?.Type ?? exp4.Type; + switch (memberType.FullName) + { + case "System.String": extRet = ExpressionLambdaToSqlMemberAccessString(exp4, tsc); break; + case "System.DateTime": extRet = ExpressionLambdaToSqlMemberAccessDateTime(exp4, tsc); break; + case "System.TimeSpan": extRet = ExpressionLambdaToSqlMemberAccessTimeSpan(exp4, tsc); break; + } + if (string.IsNullOrEmpty(extRet) == false) return extRet; + var other4Exp = ExpressionLambdaToSqlOther(exp4, tsc); + if (string.IsNullOrEmpty(other4Exp) == false) return other4Exp; + } + var expStack = new Stack(); + expStack.Push(exp); + MethodCallExpression callExp = null; + var exp2 = exp4?.Expression; + while (true) + { + switch (exp2?.NodeType) + { + case ExpressionType.Constant: + expStack.Push(exp2); + break; + case ExpressionType.Parameter: + expStack.Push(exp2); + break; + case ExpressionType.MemberAccess: + expStack.Push(exp2); + exp2 = (exp2 as MemberExpression).Expression; + if (exp2 == null) break; + continue; + case ExpressionType.Call: + callExp = exp2 as MethodCallExpression; + expStack.Push(exp2); + exp2 = callExp.Object; + if (exp2 == null) break; + continue; + case ExpressionType.TypeAs: + case ExpressionType.Convert: + var oper2 = (exp2 as UnaryExpression).Operand; + if (oper2.NodeType == ExpressionType.Parameter) + { + var oper2Parm = oper2 as ParameterExpression; + expStack.Push(Expression.Parameter(exp2.Type, oper2Parm.Name)); + } + else + expStack.Push(oper2); + break; + } + break; + } + if (expStack.First().NodeType != ExpressionType.Parameter) return formatSql(Expression.Lambda(exp).Compile().DynamicInvoke(), tsc.mapType); + if (callExp != null) return ExpressionLambdaToSql(callExp, tsc); + if (tsc.getSelectGroupingMapString != null && expStack.First().Type.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) + { + if (tsc.getSelectGroupingMapString != null) + { + var expText = tsc.getSelectGroupingMapString(expStack.Where((a, b) => b >= 2).ToArray()); + if (string.IsNullOrEmpty(expText) == false) return expText; + } + } - TableInfo tb2 = null; - ParameterExpression parmExp2 = null; - string alias2 = "", name2 = ""; - SelectTableInfo find2 = null; - while (expStack.Count > 0) { - exp2 = expStack.Pop(); - switch (exp2.NodeType) { - case ExpressionType.Constant: - throw new NotImplementedException("未实现 MemberAccess 下的 Constant"); - case ExpressionType.Parameter: - case ExpressionType.MemberAccess: - - var exp2Type = exp2.Type; - if (exp2Type.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) exp2Type = exp2Type.GenericTypeArguments.LastOrDefault() ?? exp2.Type; - var tb2tmp = _common.GetTableByEntity(exp2Type); - var mp2 = exp2 as MemberExpression; - if (mp2?.Member.Name == "Key" && mp2.Expression.Type.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) continue; - if (tb2tmp != null) { - if (exp2.NodeType == ExpressionType.Parameter) { - parmExp2 = (exp2 as ParameterExpression); - alias2 = parmExp2.Name; - } else alias2 = $"{alias2}__{mp2.Member.Name}"; - find2 = getOrAddTable(tb2tmp, alias2, exp2.NodeType == ExpressionType.Parameter, parmExp2, mp2); - alias2 = find2.Alias; - tb2 = tb2tmp; - } - if (exp2.NodeType == ExpressionType.Parameter && expStack.Any() == false) { //附加选择的参数所有列 - if (tsc._selectColumnMap != null) { - foreach (var tb2c in tb2.Columns.Values) - tsc._selectColumnMap.Add(new SelectColumnInfo { Table = find2, Column = tb2c }); - if (tb2.Columns.Any()) return ""; - } - } - if (mp2 == null || expStack.Any()) continue; - if (tb2.ColumnsByCs.ContainsKey(mp2.Member.Name) == false) { //如果选的是对象,附加所有列 - if (tsc._selectColumnMap != null) { - var tb3 = _common.GetTableByEntity(mp2.Type); - if (tb3 != null) { - var find3 = getOrAddTable(tb2tmp, alias2 /*$"{alias2}__{mp2.Member.Name}"*/, exp2.NodeType == ExpressionType.Parameter, parmExp2, mp2); + if (tsc._tables == null) + { + var pp = expStack.Pop() as ParameterExpression; + var memberExp = expStack.Pop() as MemberExpression; + var tb = _common.GetTableByEntity(pp.Type); + if (tb.ColumnsByCs.ContainsKey(memberExp.Member.Name) == false) throw new ArgumentException($"{tb.DbName} 找不到列 {memberExp.Member.Name}"); + if (tsc._selectColumnMap != null) + { + tsc._selectColumnMap.Add(new SelectColumnInfo { Table = null, Column = tb.ColumnsByCs[memberExp.Member.Name] }); + } + var name = tb.ColumnsByCs[memberExp.Member.Name].Attribute.Name; + if (tsc.isQuoteName) name = _common.QuoteSqlName(name); + return name; + } + Func getOrAddTable = (tbtmp, alias, isa, parmExp, mp) => + { + var finds = new SelectTableInfo[0]; + if (tsc.style == ExpressionStyle.SelectColumns) + { + finds = tsc._tables.Where(a => a.Table.Type == tbtmp.Type).ToArray(); + if (finds.Any()) finds = new[] { finds.First() }; + } + if (finds.Length != 1 && isa && parmExp != null) + finds = tsc._tables.Where(a => a.Parameter == parmExp).ToArray(); + if (finds.Length != 1) + { + var navdot = string.IsNullOrEmpty(alias) ? new SelectTableInfo[0] : tsc._tables.Where(a2 => a2.Parameter != null && alias.StartsWith($"{a2.Alias}__")).ToArray(); + if (navdot.Length > 0) + { + var isthis = navdot[0] == tsc._tables[0]; + finds = tsc._tables.Where(a2 => (isa && a2.Parameter != null || !isa && a2.Parameter == null) && + a2.Table.Type == tbtmp.Type && a2.Alias == alias && a2.Alias.StartsWith($"{navdot[0].Alias}__") && + (isthis && a2.Type != SelectTableInfoType.Parent || !isthis && a2.Type == SelectTableInfoType.Parent)).ToArray(); + if (finds.Length == 0) + finds = tsc._tables.Where(a2 => + a2.Table.Type == tbtmp.Type && a2.Alias == alias && a2.Alias.StartsWith($"{navdot[0].Alias}__") && + (isthis && a2.Type != SelectTableInfoType.Parent || !isthis && a2.Type == SelectTableInfoType.Parent)).ToArray(); + } + else + { + finds = tsc._tables.Where(a2 => (isa && a2.Parameter != null || isa && a2.Parameter == null) && + a2.Table.Type == tbtmp.Type && a2.Alias == alias).ToArray(); + if (finds.Length != 1) + { + finds = tsc._tables.Where(a2 => (isa && a2.Parameter != null || isa && a2.Parameter == null) && + a2.Table.Type == tbtmp.Type).ToArray(); + if (finds.Length != 1) + { + finds = tsc._tables.Where(a2 => (isa && a2.Parameter != null || isa && a2.Parameter == null) && + a2.Table.Type == tbtmp.Type).ToArray(); + if (finds.Length != 1) + finds = tsc._tables.Where(a2 => a2.Table.Type == tbtmp.Type).ToArray(); + } + } + } + //finds = tsc._tables.Where((a2, c2) => (isa || a2.Parameter == null) && a2.Table.CsName == tbtmp.CsName && (isthis && a2.Type != SelectTableInfoType.Parent || !isthis)).ToArray(); //外部表,内部表一起查 + //if (finds.Length > 1) { + // finds = tsc._tables.Where((a2, c2) => (isa || a2.Parameter == null) && a2.Table.CsName == tbtmp.CsName && a2.Type == SelectTableInfoType.Parent && a2.Alias == alias).ToArray(); //查询外部表 + // if (finds.Any() == false) { + // finds = tsc._tables.Where((a2, c2) => (isa || a2.Parameter == null) && a2.Table.CsName == tbtmp.CsName && a2.Type != SelectTableInfoType.Parent).ToArray(); //查询内部表 + // if (finds.Length > 1) + // finds = tsc._tables.Where((a2, c2) => (isa || a2.Parameter == null) && a2.Table.CsName == tbtmp.CsName && a2.Type != SelectTableInfoType.Parent && a2.Alias == alias).ToArray(); + // } + //} + } + var find = finds.Length == 1 ? finds.First() : null; + if (find != null && isa && parmExp != null && find.Parameter != parmExp) + find.Parameter = parmExp; + if (find == null) + { + tsc._tables.Add(find = new SelectTableInfo { Table = tbtmp, Alias = alias, On = null, Type = mp == null ? tsc.tbtype : SelectTableInfoType.LeftJoin, Parameter = isa ? parmExp : null }); + if (mp?.Expression != null) + { //导航条件,OneToOne、ManyToOne + var firstTb = tsc._tables.First().Table; + var parentTb = _common.GetTableByEntity(mp.Expression.Type); + var parentTbRef = parentTb?.GetTableRef(mp.Member.Name, tsc.style == ExpressionStyle.AsSelect); + if (parentTbRef != null) + { + Expression navCondExp = null; + for (var mn = 0; mn < parentTbRef.Columns.Count; mn++) + { + var col1 = parentTbRef.RefColumns[mn]; + var col2 = parentTbRef.Columns[mn]; + var pexp1 = Expression.Property(mp, col1.CsName); + var pexp2 = Expression.Property(mp.Expression, col2.CsName); + if (col1.CsType != col2.CsType) + { + if (col1.CsType.IsNullableType()) pexp1 = Expression.Property(pexp1, _dicNullableValueProperty.GetOrAdd(col1.CsType, ct1 => ct1.GetProperty("Value"))); + if (col2.CsType.IsNullableType()) pexp2 = Expression.Property(pexp2, _dicNullableValueProperty.GetOrAdd(col2.CsType, ct2 => ct2.GetProperty("Value"))); + } + var tmpExp = Expression.Equal(pexp1, pexp2); + if (mn == 0) navCondExp = tmpExp; + else navCondExp = Expression.AndAlso(navCondExp, tmpExp); + } + if (find.Type == SelectTableInfoType.InnerJoin || + find.Type == SelectTableInfoType.LeftJoin || + find.Type == SelectTableInfoType.RightJoin) + find.On = ExpressionLambdaToSql(navCondExp, tsc.CloneSetgetSelectGroupingMapStringAndgetSelectGroupingMapStringAndtbtype(null, null, find.Type)); + else + find.NavigateCondition = ExpressionLambdaToSql(navCondExp, tsc.CloneSetgetSelectGroupingMapStringAndgetSelectGroupingMapStringAndtbtype(null, null, find.Type)); + } + } + } + return find; + }; - foreach (var tb3c in tb3.Columns.Values) - tsc._selectColumnMap.Add(new SelectColumnInfo { Table = find3, Column = tb3c }); - if (tb3.Columns.Any()) return ""; - } - } - throw new ArgumentException($"{tb2.DbName} 找不到列 {mp2.Member.Name}"); - } - var col2 = tb2.ColumnsByCs[mp2.Member.Name]; - if (tsc._selectColumnMap != null && find2 != null) { - tsc._selectColumnMap.Add(new SelectColumnInfo { Table = find2, Column = col2 }); - return ""; - } - name2 = tb2.ColumnsByCs[mp2.Member.Name].Attribute.Name; - break; - case ExpressionType.Call:break; - } - } - if (tsc.isQuoteName) name2 = _common.QuoteSqlName(name2); - return $"{alias2}.{name2}"; - } - var expBinary = exp as BinaryExpression; - if (expBinary == null) { - var other99Exp = ExpressionLambdaToSqlOther(exp, tsc); - if (string.IsNullOrEmpty(other99Exp) == false) return other99Exp; - return ""; - } - switch (expBinary.NodeType) { - case ExpressionType.Coalesce: - return _common.IsNull(ExpressionLambdaToSql(expBinary.Left, tsc), ExpressionLambdaToSql(expBinary.Right, tsc)); - } - if (dicExpressionOperator.TryGetValue(expBinary.NodeType, out var tryoper) == false) return ""; - return ExpressionBinary(tryoper, expBinary.Left, expBinary.Right, tsc); - } + TableInfo tb2 = null; + ParameterExpression parmExp2 = null; + string alias2 = "", name2 = ""; + SelectTableInfo find2 = null; + while (expStack.Count > 0) + { + exp2 = expStack.Pop(); + switch (exp2.NodeType) + { + case ExpressionType.Constant: + throw new NotImplementedException("未实现 MemberAccess 下的 Constant"); + case ExpressionType.Parameter: + case ExpressionType.MemberAccess: - public abstract string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc); - public abstract string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc); - public abstract string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc); - public abstract string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc); - public abstract string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc); - public abstract string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc); - public abstract string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc); - public abstract string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc); - public abstract string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc); + var exp2Type = exp2.Type; + if (exp2Type.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) exp2Type = exp2Type.GenericTypeArguments.LastOrDefault() ?? exp2.Type; + var tb2tmp = _common.GetTableByEntity(exp2Type); + var mp2 = exp2 as MemberExpression; + if (mp2?.Member.Name == "Key" && mp2.Expression.Type.FullName.StartsWith("FreeSql.ISelectGroupingAggregate`")) continue; + if (tb2tmp != null) + { + if (exp2.NodeType == ExpressionType.Parameter) + { + parmExp2 = (exp2 as ParameterExpression); + alias2 = parmExp2.Name; + } + else alias2 = $"{alias2}__{mp2.Member.Name}"; + find2 = getOrAddTable(tb2tmp, alias2, exp2.NodeType == ExpressionType.Parameter, parmExp2, mp2); + alias2 = find2.Alias; + tb2 = tb2tmp; + } + if (exp2.NodeType == ExpressionType.Parameter && expStack.Any() == false) + { //附加选择的参数所有列 + if (tsc._selectColumnMap != null) + { + foreach (var tb2c in tb2.Columns.Values) + tsc._selectColumnMap.Add(new SelectColumnInfo { Table = find2, Column = tb2c }); + if (tb2.Columns.Any()) return ""; + } + } + if (mp2 == null || expStack.Any()) continue; + if (tb2.ColumnsByCs.ContainsKey(mp2.Member.Name) == false) + { //如果选的是对象,附加所有列 + if (tsc._selectColumnMap != null) + { + var tb3 = _common.GetTableByEntity(mp2.Type); + if (tb3 != null) + { + var find3 = getOrAddTable(tb2tmp, alias2 /*$"{alias2}__{mp2.Member.Name}"*/, exp2.NodeType == ExpressionType.Parameter, parmExp2, mp2); - public enum ExpressionStyle { - Where, AsSelect, SelectColumns - } - public class ExpTSC { - public List _tables { get; set; } - public List _selectColumnMap { get; set; } - public Func getSelectGroupingMapString { get; set; } - public SelectTableInfoType tbtype { get; set; } - public bool isQuoteName { get; set; } - public bool isDisableDiyParse { get; set; } - public ExpressionStyle style { get; set; } - public Type mapType { get; set; } - public TableInfo currentTable { get; set; } + foreach (var tb3c in tb3.Columns.Values) + tsc._selectColumnMap.Add(new SelectColumnInfo { Table = find3, Column = tb3c }); + if (tb3.Columns.Any()) return ""; + } + } + throw new ArgumentException($"{tb2.DbName} 找不到列 {mp2.Member.Name}"); + } + var col2 = tb2.ColumnsByCs[mp2.Member.Name]; + if (tsc._selectColumnMap != null && find2 != null) + { + tsc._selectColumnMap.Add(new SelectColumnInfo { Table = find2, Column = col2 }); + return ""; + } + name2 = tb2.ColumnsByCs[mp2.Member.Name].Attribute.Name; + break; + case ExpressionType.Call: break; + } + } + if (tsc.isQuoteName) name2 = _common.QuoteSqlName(name2); + return $"{alias2}.{name2}"; + } + var expBinary = exp as BinaryExpression; + if (expBinary == null) + { + var other99Exp = ExpressionLambdaToSqlOther(exp, tsc); + if (string.IsNullOrEmpty(other99Exp) == false) return other99Exp; + return ""; + } + switch (expBinary.NodeType) + { + case ExpressionType.Coalesce: + return _common.IsNull(ExpressionLambdaToSql(expBinary.Left, tsc), ExpressionLambdaToSql(expBinary.Right, tsc)); + } + if (dicExpressionOperator.TryGetValue(expBinary.NodeType, out var tryoper) == false) return ""; + return ExpressionBinary(tryoper, expBinary.Left, expBinary.Right, tsc); + } - public ExpTSC CloneSetgetSelectGroupingMapStringAndgetSelectGroupingMapStringAndtbtype(List v1, Func v2, SelectTableInfoType v3 ) { - return new ExpTSC { - _tables = this._tables, - _selectColumnMap = v1, - getSelectGroupingMapString = v2, - tbtype = v3, - isQuoteName = this.isQuoteName, - isDisableDiyParse = this.isDisableDiyParse, - style = this.style, - currentTable = this.currentTable - }; - } - public ExpTSC CloneDisableDiyParse() { - return new ExpTSC { - _tables = this._tables, - _selectColumnMap = this._selectColumnMap, - getSelectGroupingMapString = this.getSelectGroupingMapString, - tbtype = this.tbtype, - isQuoteName = this.isQuoteName, - isDisableDiyParse = true, - style = this.style, - currentTable = this.currentTable - }; - } - } + public abstract string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc); + public abstract string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc); + public abstract string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc); + public abstract string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc); + public abstract string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc); + public abstract string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc); + public abstract string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc); + public abstract string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc); + public abstract string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc); - public string formatSql(object obj, Type mapType) { - return string.Concat(_ado.AddslashesProcessParam(obj, mapType)); - } - } + public enum ExpressionStyle + { + Where, AsSelect, SelectColumns + } + public class ExpTSC + { + public List _tables { get; set; } + public List _selectColumnMap { get; set; } + public Func getSelectGroupingMapString { get; set; } + public SelectTableInfoType tbtype { get; set; } + public bool isQuoteName { get; set; } + public bool isDisableDiyParse { get; set; } + public ExpressionStyle style { get; set; } + public Type mapType { get; set; } + public TableInfo currentTable { get; set; } + + public ExpTSC CloneSetgetSelectGroupingMapStringAndgetSelectGroupingMapStringAndtbtype(List v1, Func v2, SelectTableInfoType v3) + { + return new ExpTSC + { + _tables = this._tables, + _selectColumnMap = v1, + getSelectGroupingMapString = v2, + tbtype = v3, + isQuoteName = this.isQuoteName, + isDisableDiyParse = this.isDisableDiyParse, + style = this.style, + currentTable = this.currentTable + }; + } + public ExpTSC CloneDisableDiyParse() + { + return new ExpTSC + { + _tables = this._tables, + _selectColumnMap = this._selectColumnMap, + getSelectGroupingMapString = this.getSelectGroupingMapString, + tbtype = this.tbtype, + isQuoteName = this.isQuoteName, + isDisableDiyParse = true, + style = this.style, + currentTable = this.currentTable + }; + } + } + + public string formatSql(object obj, Type mapType) + { + return string.Concat(_ado.AddslashesProcessParam(obj, mapType)); + } + } } diff --git a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProvider.cs b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProvider.cs index 1f0d5236..1ab01b5d 100644 --- a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProvider.cs +++ b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProvider.cs @@ -9,694 +9,795 @@ using System.Linq; using System.Text; using System.Reflection; -namespace FreeSql.Internal.CommonProvider { - public abstract partial class AdoProvider : IAdo, IDisposable { +namespace FreeSql.Internal.CommonProvider +{ + public abstract partial class AdoProvider : IAdo, IDisposable + { - protected abstract void ReturnConnection(ObjectPool pool, Object conn, Exception ex); - protected abstract DbCommand CreateCommand(); - protected abstract DbParameter[] GetDbParamtersByObject(string sql, object obj); - public Action AopCommandExecuting { get; set; } - public Action AopCommandExecuted { get; set; } + protected abstract void ReturnConnection(ObjectPool pool, Object conn, Exception ex); + protected abstract DbCommand CreateCommand(); + protected abstract DbParameter[] GetDbParamtersByObject(string sql, object obj); + public Action AopCommandExecuting { get; set; } + public Action AopCommandExecuted { get; set; } - protected bool IsTracePerformance => AopCommandExecuted != null; - - public ObjectPool MasterPool { get; protected set; } - public List> SlavePools { get; } = new List>(); - public DataType DataType { get; } - protected CommonUtils _util { get; set; } - protected int slaveUnavailables = 0; - private object slaveLock = new object(); - private Random slaveRandom = new Random(); + protected bool IsTracePerformance => AopCommandExecuted != null; - public AdoProvider(DataType dataType) { - this.DataType = dataType; - } + public ObjectPool MasterPool { get; protected set; } + public List> SlavePools { get; } = new List>(); + public DataType DataType { get; } + protected CommonUtils _util { get; set; } + protected int slaveUnavailables = 0; + private object slaveLock = new object(); + private Random slaveRandom = new Random(); - void LoggerException(ObjectPool pool, (DbCommand cmd, bool isclose) pc, Exception e, DateTime dt, StringBuilder logtxt, bool isThrowException = true) { - var cmd = pc.cmd; - if (pc.isclose) pc.cmd.Connection.Close(); - if (IsTracePerformance) { - TimeSpan ts = DateTime.Now.Subtract(dt); - if (e == null && ts.TotalMilliseconds > 100) - Trace.WriteLine(logtxt.Insert(0, $"{pool?.Policy.Name}(执行SQL)语句耗时过长{ts.TotalMilliseconds}ms\r\n{cmd.CommandText}\r\n").ToString()); - else - logtxt.Insert(0, $"{pool?.Policy.Name}(执行SQL)耗时{ts.TotalMilliseconds}ms\r\n{cmd.CommandText}\r\n").ToString(); - } + public AdoProvider(DataType dataType) + { + this.DataType = dataType; + } - if (e == null) { - AopCommandExecuted?.Invoke(cmd, logtxt.ToString()); - return; - } + void LoggerException(ObjectPool pool, (DbCommand cmd, bool isclose) pc, Exception e, DateTime dt, StringBuilder logtxt, bool isThrowException = true) + { + var cmd = pc.cmd; + if (pc.isclose) pc.cmd.Connection.Close(); + if (IsTracePerformance) + { + TimeSpan ts = DateTime.Now.Subtract(dt); + if (e == null && ts.TotalMilliseconds > 100) + Trace.WriteLine(logtxt.Insert(0, $"{pool?.Policy.Name}(执行SQL)语句耗时过长{ts.TotalMilliseconds}ms\r\n{cmd.CommandText}\r\n").ToString()); + else + logtxt.Insert(0, $"{pool?.Policy.Name}(执行SQL)耗时{ts.TotalMilliseconds}ms\r\n{cmd.CommandText}\r\n").ToString(); + } - StringBuilder log = new StringBuilder(); - log.Append(pool?.Policy.Name).Append("数据库出错(执行SQL)〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓\r\n").Append(cmd.CommandText).Append("\r\n"); - foreach (DbParameter parm in cmd.Parameters) - log.Append(parm.ParameterName.PadRight(20, ' ')).Append(" = ").Append((parm.Value ?? DBNull.Value) == DBNull.Value ? "NULL" : parm.Value).Append("\r\n"); + if (e == null) + { + AopCommandExecuted?.Invoke(cmd, logtxt.ToString()); + return; + } - log.Append(e.Message); - Trace.WriteLine(log.ToString()); + StringBuilder log = new StringBuilder(); + log.Append(pool?.Policy.Name).Append("数据库出错(执行SQL)〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓\r\n").Append(cmd.CommandText).Append("\r\n"); + foreach (DbParameter parm in cmd.Parameters) + log.Append(parm.ParameterName.PadRight(20, ' ')).Append(" = ").Append((parm.Value ?? DBNull.Value) == DBNull.Value ? "NULL" : parm.Value).Append("\r\n"); - if (cmd.Transaction != null) { - var curTran = TransactionCurrentThread; - if (cmd.Transaction != TransactionCurrentThread) { - //cmd.Transaction.Rollback(); - } else - RollbackTransaction(); - } + log.Append(e.Message); + Trace.WriteLine(log.ToString()); - AopCommandExecuted?.Invoke(cmd, log.ToString()); + if (cmd.Transaction != null) + { + var curTran = TransactionCurrentThread; + if (cmd.Transaction != TransactionCurrentThread) + { + //cmd.Transaction.Rollback(); + } + else + RollbackTransaction(); + } - cmd.Parameters.Clear(); - if (isThrowException) throw e; - } + AopCommandExecuted?.Invoke(cmd, log.ToString()); - internal static ConcurrentDictionary> dicQueryTypeGetProperties = new ConcurrentDictionary>(); - internal Dictionary GetQueryTypeProperties(Type type) { - var tb = _util.GetTableByEntity(type); - var props = tb?.Properties ?? dicQueryTypeGetProperties.GetOrAdd(type, k => type.GetProperties().ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase)); - return props; - } - public List Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public List Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public List Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public List Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); - public List Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); - public List Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - var ret = new List(); - if (string.IsNullOrEmpty(cmdText)) return ret; - var type = typeof(T); - string flag = null; - int[] indexes = null; - var props = GetQueryTypeProperties(type); - ExecuteReader(connection, transaction, dr => { - if (indexes == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes = props.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag = sbflag.ToString(); - } - ret.Add((T)Utils.ExecuteArrayRowReadClassOrTuple(flag, type, indexes, dr, 0, _util).Value); - }, cmdType, cmdText, cmdParms); - return ret; - } - #region query multi - public (List, List) Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List) Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); - public (List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); - public (List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return (new List(), new List()); - var ret1 = new List(); - var type1 = typeof(T1); - string flag1 = null; - int[] indexes1 = null; - var props1 = GetQueryTypeProperties(type1); + cmd.Parameters.Clear(); + if (isThrowException) throw e; + } - var ret2 = new List(); - var type2 = typeof(T2); - string flag2 = null; - int[] indexes2 = null; - var props2 = GetQueryTypeProperties(type2); - ExecuteReaderMultiple(2, connection, transaction, (dr, result) => { - switch(result) { - case 0: - if (indexes1 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag1 = sbflag.ToString(); - } - ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); - break; - case 1: - if (indexes2 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag2 = sbflag.ToString(); - } - ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); - break; - } - }, cmdType, cmdText, cmdParms); - return (ret1, ret2); - } + internal static ConcurrentDictionary> dicQueryTypeGetProperties = new ConcurrentDictionary>(); + internal Dictionary GetQueryTypeProperties(Type type) + { + var tb = _util.GetTableByEntity(type); + var props = tb?.Properties ?? dicQueryTypeGetProperties.GetOrAdd(type, k => type.GetProperties().ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase)); + return props; + } + public List Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public List Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public List Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public List Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); + public List Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); + public List Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + var ret = new List(); + if (string.IsNullOrEmpty(cmdText)) return ret; + var type = typeof(T); + string flag = null; + int[] indexes = null; + var props = GetQueryTypeProperties(type); + ExecuteReader(connection, transaction, dr => + { + if (indexes == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes = props.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag = sbflag.ToString(); + } + ret.Add((T)Utils.ExecuteArrayRowReadClassOrTuple(flag, type, indexes, dr, 0, _util).Value); + }, cmdType, cmdText, cmdParms); + return ret; + } + #region query multi + public (List, List) Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List) Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); + public (List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); + public (List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return (new List(), new List()); + var ret1 = new List(); + var type1 = typeof(T1); + string flag1 = null; + int[] indexes1 = null; + var props1 = GetQueryTypeProperties(type1); - public (List, List, List) Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); - public (List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); - public (List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List()); - var ret1 = new List(); - var type1 = typeof(T1); - string flag1 = null; - int[] indexes1 = null; - var props1 = GetQueryTypeProperties(type1); + var ret2 = new List(); + var type2 = typeof(T2); + string flag2 = null; + int[] indexes2 = null; + var props2 = GetQueryTypeProperties(type2); + ExecuteReaderMultiple(2, connection, transaction, (dr, result) => + { + switch (result) + { + case 0: + if (indexes1 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag1 = sbflag.ToString(); + } + ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); + break; + case 1: + if (indexes2 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag2 = sbflag.ToString(); + } + ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); + break; + } + }, cmdType, cmdText, cmdParms); + return (ret1, ret2); + } - var ret2 = new List(); - var type2 = typeof(T2); - string flag2 = null; - int[] indexes2 = null; - var props2 = GetQueryTypeProperties(type2); + public (List, List, List) Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); + public (List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); + public (List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List()); + var ret1 = new List(); + var type1 = typeof(T1); + string flag1 = null; + int[] indexes1 = null; + var props1 = GetQueryTypeProperties(type1); - var ret3 = new List(); - var type3 = typeof(T3); - string flag3 = null; - int[] indexes3 = null; - var props3 = GetQueryTypeProperties(type3); - ExecuteReaderMultiple(3, connection, transaction, (dr, result) => { - switch (result) { - case 0: - if (indexes1 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag1 = sbflag.ToString(); - } - ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); - break; - case 1: - if (indexes2 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag2 = sbflag.ToString(); - } - ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); - break; - case 2: - if (indexes3 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag3 = sbflag.ToString(); - } - ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); - break; - } - }, cmdType, cmdText, cmdParms); - return (ret1, ret2, ret3); - } + var ret2 = new List(); + var type2 = typeof(T2); + string flag2 = null; + int[] indexes2 = null; + var props2 = GetQueryTypeProperties(type2); - public (List, List, List, List) Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); - public (List, List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); - public (List, List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List(), new List()); - var ret1 = new List(); - var type1 = typeof(T1); - string flag1 = null; - int[] indexes1 = null; - var props1 = GetQueryTypeProperties(type1); + var ret3 = new List(); + var type3 = typeof(T3); + string flag3 = null; + int[] indexes3 = null; + var props3 = GetQueryTypeProperties(type3); + ExecuteReaderMultiple(3, connection, transaction, (dr, result) => + { + switch (result) + { + case 0: + if (indexes1 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag1 = sbflag.ToString(); + } + ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); + break; + case 1: + if (indexes2 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag2 = sbflag.ToString(); + } + ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); + break; + case 2: + if (indexes3 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag3 = sbflag.ToString(); + } + ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); + break; + } + }, cmdType, cmdText, cmdParms); + return (ret1, ret2, ret3); + } - var ret2 = new List(); - var type2 = typeof(T2); - string flag2 = null; - int[] indexes2 = null; - var props2 = GetQueryTypeProperties(type2); + public (List, List, List, List) Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); + public (List, List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); + public (List, List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List(), new List()); + var ret1 = new List(); + var type1 = typeof(T1); + string flag1 = null; + int[] indexes1 = null; + var props1 = GetQueryTypeProperties(type1); - var ret3 = new List(); - var type3 = typeof(T3); - string flag3 = null; - int[] indexes3 = null; - var props3 = GetQueryTypeProperties(type3); + var ret2 = new List(); + var type2 = typeof(T2); + string flag2 = null; + int[] indexes2 = null; + var props2 = GetQueryTypeProperties(type2); - var ret4 = new List(); - var type4 = typeof(T4); - string flag4 = null; - int[] indexes4 = null; - var props4 = GetQueryTypeProperties(type4); - ExecuteReaderMultiple(4, connection, transaction, (dr, result) => { - switch (result) { - case 0: - if (indexes1 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag1 = sbflag.ToString(); - } - ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); - break; - case 1: - if (indexes2 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag2 = sbflag.ToString(); - } - ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); - break; - case 2: - if (indexes3 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag3 = sbflag.ToString(); - } - ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); - break; - case 3: - if (indexes4 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes4 = props4.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag4 = sbflag.ToString(); - } - ret4.Add((T4)Utils.ExecuteArrayRowReadClassOrTuple(flag4, type4, indexes4, dr, 0, _util).Value); - break; - } - }, cmdType, cmdText, cmdParms); - return (ret1, ret2, ret3, ret4); - } + var ret3 = new List(); + var type3 = typeof(T3); + string flag3 = null; + int[] indexes3 = null; + var props3 = GetQueryTypeProperties(type3); - public (List, List, List, List, List) Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public (List, List, List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); - public (List, List, List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); - public (List, List, List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List(), new List(), new List()); - var ret1 = new List(); - var type1 = typeof(T1); - string flag1 = null; - int[] indexes1 = null; - var props1 = GetQueryTypeProperties(type1); + var ret4 = new List(); + var type4 = typeof(T4); + string flag4 = null; + int[] indexes4 = null; + var props4 = GetQueryTypeProperties(type4); + ExecuteReaderMultiple(4, connection, transaction, (dr, result) => + { + switch (result) + { + case 0: + if (indexes1 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag1 = sbflag.ToString(); + } + ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); + break; + case 1: + if (indexes2 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag2 = sbflag.ToString(); + } + ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); + break; + case 2: + if (indexes3 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag3 = sbflag.ToString(); + } + ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); + break; + case 3: + if (indexes4 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes4 = props4.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag4 = sbflag.ToString(); + } + ret4.Add((T4)Utils.ExecuteArrayRowReadClassOrTuple(flag4, type4, indexes4, dr, 0, _util).Value); + break; + } + }, cmdType, cmdText, cmdParms); + return (ret1, ret2, ret3, ret4); + } - var ret2 = new List(); - var type2 = typeof(T2); - string flag2 = null; - int[] indexes2 = null; - var props2 = GetQueryTypeProperties(type2); + public (List, List, List, List, List) Query(string cmdText, object parms = null) => Query(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List, List, List) Query(DbTransaction transaction, string cmdText, object parms = null) => Query(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List, List, List) Query(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => Query(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public (List, List, List, List, List) Query(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, null, cmdType, cmdText, cmdParms); + public (List, List, List, List, List) Query(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => Query(null, transaction, cmdType, cmdText, cmdParms); + public (List, List, List, List, List) Query(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List(), new List(), new List()); + var ret1 = new List(); + var type1 = typeof(T1); + string flag1 = null; + int[] indexes1 = null; + var props1 = GetQueryTypeProperties(type1); - var ret3 = new List(); - var type3 = typeof(T3); - string flag3 = null; - int[] indexes3 = null; - var props3 = GetQueryTypeProperties(type3); + var ret2 = new List(); + var type2 = typeof(T2); + string flag2 = null; + int[] indexes2 = null; + var props2 = GetQueryTypeProperties(type2); - var ret4 = new List(); - var type4 = typeof(T4); - string flag4 = null; - int[] indexes4 = null; - var props4 = GetQueryTypeProperties(type4); + var ret3 = new List(); + var type3 = typeof(T3); + string flag3 = null; + int[] indexes3 = null; + var props3 = GetQueryTypeProperties(type3); - var ret5 = new List(); - var type5 = typeof(T5); - string flag5 = null; - int[] indexes5 = null; - var props5 = GetQueryTypeProperties(type5); - ExecuteReaderMultiple(5, connection, transaction, (dr, result) => { - switch (result) { - case 0: - if (indexes1 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag1 = sbflag.ToString(); - } - ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); - break; - case 1: - if (indexes2 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag2 = sbflag.ToString(); - } - ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); - break; - case 2: - if (indexes3 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag3 = sbflag.ToString(); - } - ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); - break; - case 3: - if (indexes4 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes4 = props4.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag4 = sbflag.ToString(); - } - ret4.Add((T4)Utils.ExecuteArrayRowReadClassOrTuple(flag4, type4, indexes4, dr, 0, _util).Value); - break; - case 4: - if (indexes5 == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes5 = props5.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag5 = sbflag.ToString(); - } - ret5.Add((T5)Utils.ExecuteArrayRowReadClassOrTuple(flag5, type5, indexes5, dr, 0, _util).Value); - break; - } - }, cmdType, cmdText, cmdParms); - return (ret1, ret2, ret3, ret4, ret5); - } - #endregion + var ret4 = new List(); + var type4 = typeof(T4); + string flag4 = null; + int[] indexes4 = null; + var props4 = GetQueryTypeProperties(type4); - public void ExecuteReader(Action readerHander, string cmdText, object parms = null) => ExecuteReader(null, null, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public void ExecuteReader(DbTransaction transaction, Action readerHander, string cmdText, object parms = null) => ExecuteReader(null, transaction, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public void ExecuteReader(DbConnection connection, DbTransaction transaction, Action readerHander, string cmdText, object parms = null) => ExecuteReader(connection, transaction, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public void ExecuteReader(Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReader(null, null, readerHander, cmdType, cmdText, cmdParms); - public void ExecuteReader(DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReader(null, transaction, readerHander, cmdType, cmdText, cmdParms); - public void ExecuteReader(DbConnection connection, DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReaderMultiple(1, connection, transaction, (dr, result) => readerHander(dr), cmdType, cmdText, cmdParms); - void ExecuteReaderMultiple(int multipleResult, DbConnection connection, DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return; - var dt = DateTime.Now; - var logtxt = new StringBuilder(); - var logtxt_dt = DateTime.Now; - var pool = this.MasterPool; - var isSlave = false; + var ret5 = new List(); + var type5 = typeof(T5); + string flag5 = null; + int[] indexes5 = null; + var props5 = GetQueryTypeProperties(type5); + ExecuteReaderMultiple(5, connection, transaction, (dr, result) => + { + switch (result) + { + case 0: + if (indexes1 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag1 = sbflag.ToString(); + } + ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); + break; + case 1: + if (indexes2 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag2 = sbflag.ToString(); + } + ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); + break; + case 2: + if (indexes3 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag3 = sbflag.ToString(); + } + ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); + break; + case 3: + if (indexes4 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes4 = props4.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag4 = sbflag.ToString(); + } + ret4.Add((T4)Utils.ExecuteArrayRowReadClassOrTuple(flag4, type4, indexes4, dr, 0, _util).Value); + break; + case 4: + if (indexes5 == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes5 = props5.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag5 = sbflag.ToString(); + } + ret5.Add((T5)Utils.ExecuteArrayRowReadClassOrTuple(flag5, type5, indexes5, dr, 0, _util).Value); + break; + } + }, cmdType, cmdText, cmdParms); + return (ret1, ret2, ret3, ret4, ret5); + } + #endregion - if (transaction == null && connection == null) { - //读写分离规则 - if (this.SlavePools.Any() && cmdText.StartsWith("SELECT ", StringComparison.CurrentCultureIgnoreCase)) { - var availables = slaveUnavailables == 0 ? - //查从库 - this.SlavePools : ( - //查主库 - slaveUnavailables == this.SlavePools.Count ? new List>() : - //查从库可用 - this.SlavePools.Where(sp => sp.IsAvailable).ToList()); - if (availables.Any()) { - isSlave = true; - pool = availables.Count == 1 ? availables[0] : availables[slaveRandom.Next(availables.Count)]; - } - } - } + public void ExecuteReader(Action readerHander, string cmdText, object parms = null) => ExecuteReader(null, null, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public void ExecuteReader(DbTransaction transaction, Action readerHander, string cmdText, object parms = null) => ExecuteReader(null, transaction, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public void ExecuteReader(DbConnection connection, DbTransaction transaction, Action readerHander, string cmdText, object parms = null) => ExecuteReader(connection, transaction, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public void ExecuteReader(Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReader(null, null, readerHander, cmdType, cmdText, cmdParms); + public void ExecuteReader(DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReader(null, transaction, readerHander, cmdType, cmdText, cmdParms); + public void ExecuteReader(DbConnection connection, DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReaderMultiple(1, connection, transaction, (dr, result) => readerHander(dr), cmdType, cmdText, cmdParms); + void ExecuteReaderMultiple(int multipleResult, DbConnection connection, DbTransaction transaction, Action readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return; + var dt = DateTime.Now; + var logtxt = new StringBuilder(); + var logtxt_dt = DateTime.Now; + var pool = this.MasterPool; + var isSlave = false; - Object conn = null; - var pc = PrepareCommand(connection, transaction, cmdType, cmdText, cmdParms, logtxt); - if (IsTracePerformance) logtxt.Append("PrepareCommand: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - Exception ex = null; - try { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - if (isSlave) { - //从库查询切换,恢复 - bool isSlaveFail = false; - try { - if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = pool.Get()).Value; - //if (slaveRandom.Next(100) % 2 == 0) throw new Exception("测试从库抛出异常"); - } catch { - isSlaveFail = true; - } - if (isSlaveFail) { - if (conn != null) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); - if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); - } - LoggerException(pool, pc, new Exception($"连接失败,准备切换其他可用服务器"), dt, logtxt, false); - pc.cmd.Parameters.Clear(); - ExecuteReaderMultiple(multipleResult, connection, transaction, readerHander, cmdType, cmdText, cmdParms); - return; - } - } else { - //主库查询 - if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = pool.Get()).Value; - } - if (IsTracePerformance) { - logtxt.Append("Open: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - logtxt_dt = DateTime.Now; - } - using (var dr = pc.cmd.ExecuteReader()) { - if (IsTracePerformance) logtxt.Append("ExecuteReader: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - int resultIndex = 0; - while (true) { - while (true) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - bool isread = dr.Read(); - if (IsTracePerformance) logtxt.Append(" dr.Read: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - if (isread == false) break; + if (transaction == null && connection == null) + { + //读写分离规则 + if (this.SlavePools.Any() && cmdText.StartsWith("SELECT ", StringComparison.CurrentCultureIgnoreCase)) + { + var availables = slaveUnavailables == 0 ? + //查从库 + this.SlavePools : ( + //查主库 + slaveUnavailables == this.SlavePools.Count ? new List>() : + //查从库可用 + this.SlavePools.Where(sp => sp.IsAvailable).ToList()); + if (availables.Any()) + { + isSlave = true; + pool = availables.Count == 1 ? availables[0] : availables[slaveRandom.Next(availables.Count)]; + } + } + } - if (readerHander != null) { - object[] values = null; - if (IsTracePerformance) { - logtxt_dt = DateTime.Now; - values = new object[dr.FieldCount]; - dr.GetValues(values); - logtxt.Append(" dr.GetValues: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - logtxt_dt = DateTime.Now; - } - readerHander(dr, resultIndex); - if (IsTracePerformance) logtxt.Append(" readerHander: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms (").Append(string.Join(", ", values)).Append(")\r\n"); - } - } - if (++resultIndex >= multipleResult || dr.NextResult() == false) break; - } - if (IsTracePerformance) logtxt_dt = DateTime.Now; - dr.Close(); - } - if (IsTracePerformance) logtxt.Append("ExecuteReader_dispose: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - } catch (Exception ex2) { - ex = ex2; - } + Object conn = null; + var pc = PrepareCommand(connection, transaction, cmdType, cmdText, cmdParms, logtxt); + if (IsTracePerformance) logtxt.Append("PrepareCommand: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + Exception ex = null; + try + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + if (isSlave) + { + //从库查询切换,恢复 + bool isSlaveFail = false; + try + { + if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = pool.Get()).Value; + //if (slaveRandom.Next(100) % 2 == 0) throw new Exception("测试从库抛出异常"); + } + catch + { + isSlaveFail = true; + } + if (isSlaveFail) + { + if (conn != null) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); + if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); + } + LoggerException(pool, pc, new Exception($"连接失败,准备切换其他可用服务器"), dt, logtxt, false); + pc.cmd.Parameters.Clear(); + ExecuteReaderMultiple(multipleResult, connection, transaction, readerHander, cmdType, cmdText, cmdParms); + return; + } + } + else + { + //主库查询 + if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = pool.Get()).Value; + } + if (IsTracePerformance) + { + logtxt.Append("Open: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + logtxt_dt = DateTime.Now; + } + using (var dr = pc.cmd.ExecuteReader()) + { + if (IsTracePerformance) logtxt.Append("ExecuteReader: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + int resultIndex = 0; + while (true) + { + while (true) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + bool isread = dr.Read(); + if (IsTracePerformance) logtxt.Append(" dr.Read: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + if (isread == false) break; - if (conn != null) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); - if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); - } - LoggerException(pool, pc, ex, dt, logtxt); - pc.cmd.Parameters.Clear(); - } - public object[][] ExecuteArray(string cmdText, object parms = null) => ExecuteArray(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public object[][] ExecuteArray(DbTransaction transaction, string cmdText, object parms = null) => ExecuteArray(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public object[][] ExecuteArray(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteArray(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public object[][] ExecuteArray(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteArray(null, null, cmdType, cmdText, cmdParms); - public object[][] ExecuteArray(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteArray(null, transaction, cmdType, cmdText, cmdParms); - public object[][] ExecuteArray(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - List ret = new List(); - ExecuteReader(connection, transaction, dr => { - object[] values = new object[dr.FieldCount]; - dr.GetValues(values); - ret.Add(values); - }, cmdType, cmdText, cmdParms); - return ret.ToArray(); - } - public DataSet ExecuteDataSet(string cmdText, object parms = null) => ExecuteDataSet(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public DataSet ExecuteDataSet(DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataSet(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public DataSet ExecuteDataSet(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataSet(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataSet(null, null, cmdType, cmdText, cmdParms); - public DataSet ExecuteDataSet(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataSet(null, transaction, cmdType, cmdText, cmdParms); - public DataSet ExecuteDataSet(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - var ret = new DataSet(); - DataTable dt = null; - ExecuteReaderMultiple(16, connection, transaction, (dr, result) => { - if (ret.Tables.Count <= result) { - dt = ret.Tables.Add(); - for (var a = 0; a < dr.FieldCount; a++) dt.Columns.Add(dr.GetName(a)); - } - object[] values = new object[dt.Columns.Count]; - dr.GetValues(values); - dt.Rows.Add(values); - }, cmdType, cmdText, cmdParms); - return ret; - } - public DataTable ExecuteDataTable(string cmdText, object parms = null) => ExecuteDataTable(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public DataTable ExecuteDataTable(DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataTable(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public DataTable ExecuteDataTable(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataTable(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public DataTable ExecuteDataTable(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataTable(null, null, cmdType, cmdText, cmdParms); - public DataTable ExecuteDataTable(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataTable(null, transaction, cmdType, cmdText, cmdParms); - public DataTable ExecuteDataTable(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - var ret = new DataTable(); - ExecuteReader(connection, transaction, dr => { - if (ret.Columns.Count == 0) - for (var a = 0; a < dr.FieldCount; a++) ret.Columns.Add(dr.GetName(a)); - object[] values = new object[ret.Columns.Count]; - dr.GetValues(values); - ret.Rows.Add(values); - }, cmdType, cmdText, cmdParms); - return ret; - } - public int ExecuteNonQuery(string cmdText, object parms = null) => ExecuteNonQuery(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public int ExecuteNonQuery(DbTransaction transaction, string cmdText, object parms = null) => ExecuteNonQuery(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public int ExecuteNonQuery(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteNonQuery(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public int ExecuteNonQuery(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteNonQuery(null, null, cmdType, cmdText, cmdParms); - public int ExecuteNonQuery(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteNonQuery(null, transaction, cmdType, cmdText, cmdParms); - public int ExecuteNonQuery(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return 0; - var dt = DateTime.Now; - var logtxt = new StringBuilder(); - var logtxt_dt = DateTime.Now; - Object conn = null; - var pc = PrepareCommand(connection, transaction, cmdType, cmdText, cmdParms, logtxt); - int val = 0; - Exception ex = null; - try { - if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = this.MasterPool.Get()).Value; - val = pc.cmd.ExecuteNonQuery(); - } catch (Exception ex2) { - ex = ex2; - } + if (readerHander != null) + { + object[] values = null; + if (IsTracePerformance) + { + logtxt_dt = DateTime.Now; + values = new object[dr.FieldCount]; + dr.GetValues(values); + logtxt.Append(" dr.GetValues: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + logtxt_dt = DateTime.Now; + } + readerHander(dr, resultIndex); + if (IsTracePerformance) logtxt.Append(" readerHander: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms (").Append(string.Join(", ", values)).Append(")\r\n"); + } + } + if (++resultIndex >= multipleResult || dr.NextResult() == false) break; + } + if (IsTracePerformance) logtxt_dt = DateTime.Now; + dr.Close(); + } + if (IsTracePerformance) logtxt.Append("ExecuteReader_dispose: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + } + catch (Exception ex2) + { + ex = ex2; + } - if (conn != null) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - ReturnConnection(MasterPool, conn, ex); //this.MasterPool.Return(conn, ex); - if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); - } - LoggerException(this.MasterPool, pc, ex, dt, logtxt); - pc.cmd.Parameters.Clear(); - return val; - } - public object ExecuteScalar(string cmdText, object parms = null) => ExecuteScalar(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public object ExecuteScalar(DbTransaction transaction, string cmdText, object parms = null) => ExecuteScalar(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public object ExecuteScalar(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteScalar(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public object ExecuteScalar(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteScalar(null, null, cmdType, cmdText, cmdParms); - public object ExecuteScalar(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteScalar(null, transaction, cmdType, cmdText, cmdParms); - public object ExecuteScalar(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return null; - var dt = DateTime.Now; - var logtxt = new StringBuilder(); - var logtxt_dt = DateTime.Now; - Object conn = null; - var pc = PrepareCommand(connection, transaction, cmdType, cmdText, cmdParms, logtxt); - object val = null; - Exception ex = null; - try { - if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = this.MasterPool.Get()).Value; - val = pc.cmd.ExecuteScalar(); - } catch (Exception ex2) { - ex = ex2; - } + if (conn != null) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); + if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); + } + LoggerException(pool, pc, ex, dt, logtxt); + pc.cmd.Parameters.Clear(); + } + public object[][] ExecuteArray(string cmdText, object parms = null) => ExecuteArray(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public object[][] ExecuteArray(DbTransaction transaction, string cmdText, object parms = null) => ExecuteArray(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public object[][] ExecuteArray(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteArray(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public object[][] ExecuteArray(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteArray(null, null, cmdType, cmdText, cmdParms); + public object[][] ExecuteArray(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteArray(null, transaction, cmdType, cmdText, cmdParms); + public object[][] ExecuteArray(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + List ret = new List(); + ExecuteReader(connection, transaction, dr => + { + object[] values = new object[dr.FieldCount]; + dr.GetValues(values); + ret.Add(values); + }, cmdType, cmdText, cmdParms); + return ret.ToArray(); + } + public DataSet ExecuteDataSet(string cmdText, object parms = null) => ExecuteDataSet(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public DataSet ExecuteDataSet(DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataSet(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public DataSet ExecuteDataSet(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataSet(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public DataSet ExecuteDataSet(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataSet(null, null, cmdType, cmdText, cmdParms); + public DataSet ExecuteDataSet(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataSet(null, transaction, cmdType, cmdText, cmdParms); + public DataSet ExecuteDataSet(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + var ret = new DataSet(); + DataTable dt = null; + ExecuteReaderMultiple(16, connection, transaction, (dr, result) => + { + if (ret.Tables.Count <= result) + { + dt = ret.Tables.Add(); + for (var a = 0; a < dr.FieldCount; a++) dt.Columns.Add(dr.GetName(a)); + } + object[] values = new object[dt.Columns.Count]; + dr.GetValues(values); + dt.Rows.Add(values); + }, cmdType, cmdText, cmdParms); + return ret; + } + public DataTable ExecuteDataTable(string cmdText, object parms = null) => ExecuteDataTable(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public DataTable ExecuteDataTable(DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataTable(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public DataTable ExecuteDataTable(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataTable(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public DataTable ExecuteDataTable(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataTable(null, null, cmdType, cmdText, cmdParms); + public DataTable ExecuteDataTable(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataTable(null, transaction, cmdType, cmdText, cmdParms); + public DataTable ExecuteDataTable(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + var ret = new DataTable(); + ExecuteReader(connection, transaction, dr => + { + if (ret.Columns.Count == 0) + for (var a = 0; a < dr.FieldCount; a++) ret.Columns.Add(dr.GetName(a)); + object[] values = new object[ret.Columns.Count]; + dr.GetValues(values); + ret.Rows.Add(values); + }, cmdType, cmdText, cmdParms); + return ret; + } + public int ExecuteNonQuery(string cmdText, object parms = null) => ExecuteNonQuery(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public int ExecuteNonQuery(DbTransaction transaction, string cmdText, object parms = null) => ExecuteNonQuery(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public int ExecuteNonQuery(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteNonQuery(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public int ExecuteNonQuery(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteNonQuery(null, null, cmdType, cmdText, cmdParms); + public int ExecuteNonQuery(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteNonQuery(null, transaction, cmdType, cmdText, cmdParms); + public int ExecuteNonQuery(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return 0; + var dt = DateTime.Now; + var logtxt = new StringBuilder(); + var logtxt_dt = DateTime.Now; + Object conn = null; + var pc = PrepareCommand(connection, transaction, cmdType, cmdText, cmdParms, logtxt); + int val = 0; + Exception ex = null; + try + { + if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = this.MasterPool.Get()).Value; + val = pc.cmd.ExecuteNonQuery(); + } + catch (Exception ex2) + { + ex = ex2; + } - if (conn != null) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - ReturnConnection(MasterPool, conn, ex); //this.MasterPool.Return(conn, ex); - if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); - } - LoggerException(this.MasterPool, pc, ex, dt, logtxt); - pc.cmd.Parameters.Clear(); - return val; - } + if (conn != null) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + ReturnConnection(MasterPool, conn, ex); //this.MasterPool.Return(conn, ex); + if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); + } + LoggerException(this.MasterPool, pc, ex, dt, logtxt); + pc.cmd.Parameters.Clear(); + return val; + } + public object ExecuteScalar(string cmdText, object parms = null) => ExecuteScalar(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public object ExecuteScalar(DbTransaction transaction, string cmdText, object parms = null) => ExecuteScalar(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public object ExecuteScalar(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteScalar(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public object ExecuteScalar(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteScalar(null, null, cmdType, cmdText, cmdParms); + public object ExecuteScalar(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteScalar(null, transaction, cmdType, cmdText, cmdParms); + public object ExecuteScalar(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return null; + var dt = DateTime.Now; + var logtxt = new StringBuilder(); + var logtxt_dt = DateTime.Now; + Object conn = null; + var pc = PrepareCommand(connection, transaction, cmdType, cmdText, cmdParms, logtxt); + object val = null; + Exception ex = null; + try + { + if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = this.MasterPool.Get()).Value; + val = pc.cmd.ExecuteScalar(); + } + catch (Exception ex2) + { + ex = ex2; + } - (DbCommand cmd, bool isclose) PrepareCommand(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, DbParameter[] cmdParms, StringBuilder logtxt) { - var dt = DateTime.Now; - DbCommand cmd = CreateCommand(); - bool isclose = false; - cmd.CommandType = cmdType; - cmd.CommandText = cmdText; + if (conn != null) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + ReturnConnection(MasterPool, conn, ex); //this.MasterPool.Return(conn, ex); + if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); + } + LoggerException(this.MasterPool, pc, ex, dt, logtxt); + pc.cmd.Parameters.Clear(); + return val; + } - if (cmdParms != null) { - foreach (var parm in cmdParms) { - if (parm == null) continue; - if (parm.Value == null) parm.Value = DBNull.Value; - cmd.Parameters.Add(parm); - } - } + (DbCommand cmd, bool isclose) PrepareCommand(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, DbParameter[] cmdParms, StringBuilder logtxt) + { + var dt = DateTime.Now; + DbCommand cmd = CreateCommand(); + bool isclose = false; + cmd.CommandType = cmdType; + cmd.CommandText = cmdText; - if (connection == null) { - var tran = transaction ?? TransactionCurrentThread; - if (IsTracePerformance) logtxt.Append(" PrepareCommand_part1: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms cmdParms: ").Append(cmd.Parameters.Count).Append("\r\n"); + if (cmdParms != null) + { + foreach (var parm in cmdParms) + { + if (parm == null) continue; + if (parm.Value == null) parm.Value = DBNull.Value; + cmd.Parameters.Add(parm); + } + } - if (tran != null && connection == null) { - if (IsTracePerformance) dt = DateTime.Now; - cmd.Connection = tran.Connection; - cmd.Transaction = tran; - if (IsTracePerformance) logtxt.Append(" PrepareCommand_tran!=null: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - } - } else { - if (connection.State != ConnectionState.Open) { - if (IsTracePerformance) dt = DateTime.Now; - connection.Open(); - if (IsTracePerformance) logtxt.Append(" PrepareCommand_ConnectionOpen: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - isclose = true; - } - cmd.Connection = connection; - if (transaction?.Connection == connection) - cmd.Transaction = transaction; - } + if (connection == null) + { + var tran = transaction ?? TransactionCurrentThread; + if (IsTracePerformance) logtxt.Append(" PrepareCommand_part1: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms cmdParms: ").Append(cmd.Parameters.Count).Append("\r\n"); - if (IsTracePerformance) dt = DateTime.Now; - AutoCommitTransaction(); - if (IsTracePerformance) logtxt.Append(" AutoCommitTransaction: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + if (tran != null && connection == null) + { + if (IsTracePerformance) dt = DateTime.Now; + cmd.Connection = tran.Connection; + cmd.Transaction = tran; + if (IsTracePerformance) logtxt.Append(" PrepareCommand_tran!=null: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + } + } + else + { + if (connection.State != ConnectionState.Open) + { + if (IsTracePerformance) dt = DateTime.Now; + connection.Open(); + if (IsTracePerformance) logtxt.Append(" PrepareCommand_ConnectionOpen: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + isclose = true; + } + cmd.Connection = connection; + if (transaction?.Connection == connection) + cmd.Transaction = transaction; + } - AopCommandExecuting?.Invoke(cmd); - return (cmd, isclose); - } - } + if (IsTracePerformance) dt = DateTime.Now; + AutoCommitTransaction(); + if (IsTracePerformance) logtxt.Append(" AutoCommitTransaction: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + + AopCommandExecuting?.Invoke(cmd); + return (cmd, isclose); + } + } } diff --git a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderAsync.cs b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderAsync.cs index 956ac42b..4a672d94 100644 --- a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderAsync.cs +++ b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderAsync.cs @@ -7,632 +7,725 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { - partial class AdoProvider { - public Task> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); - public Task> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - var ret = new List(); - if (string.IsNullOrEmpty(cmdText)) return ret; - var type = typeof(T); - string flag = null; - int[] indexes = null; - var props = GetQueryTypeProperties(type); - await ExecuteReaderAsync(connection, transaction, dr => { - if (indexes == null) { - var sbflag = new StringBuilder().Append("query"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes = props.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag = sbflag.ToString(); - } - ret.Add((T)Utils.ExecuteArrayRowReadClassOrTuple(flag, type, indexes, dr, 0, _util).Value); - return Task.FromResult(false); - }, cmdType, cmdText, cmdParms); - return ret; - } - #region QueryAsync multi - public Task<(List, List)> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); - public Task<(List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task<(List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return (new List(), new List()); - var ret1 = new List(); - var type1 = typeof(T1); - string flag1 = null; - int[] indexes1 = null; - var props1 = GetQueryTypeProperties(type1); +namespace FreeSql.Internal.CommonProvider +{ + partial class AdoProvider + { + public Task> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); + public Task> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + var ret = new List(); + if (string.IsNullOrEmpty(cmdText)) return ret; + var type = typeof(T); + string flag = null; + int[] indexes = null; + var props = GetQueryTypeProperties(type); + await ExecuteReaderAsync(connection, transaction, dr => + { + if (indexes == null) + { + var sbflag = new StringBuilder().Append("query"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes = props.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag = sbflag.ToString(); + } + ret.Add((T)Utils.ExecuteArrayRowReadClassOrTuple(flag, type, indexes, dr, 0, _util).Value); + return Task.FromResult(false); + }, cmdType, cmdText, cmdParms); + return ret; + } + #region QueryAsync multi + public Task<(List, List)> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); + public Task<(List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task<(List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return (new List(), new List()); + var ret1 = new List(); + var type1 = typeof(T1); + string flag1 = null; + int[] indexes1 = null; + var props1 = GetQueryTypeProperties(type1); - var ret2 = new List(); - var type2 = typeof(T2); - string flag2 = null; - int[] indexes2 = null; - var props2 = GetQueryTypeProperties(type2); - await ExecuteReaderMultipleAsync(2, connection, transaction, (dr, result) => { - switch (result) { - case 0: - if (indexes1 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag1 = sbflag.ToString(); - } - ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); - break; - case 1: - if (indexes2 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag2 = sbflag.ToString(); - } - ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); - break; - } - return Task.FromResult(false); - }, cmdType, cmdText, cmdParms); - return (ret1, ret2); - } + var ret2 = new List(); + var type2 = typeof(T2); + string flag2 = null; + int[] indexes2 = null; + var props2 = GetQueryTypeProperties(type2); + await ExecuteReaderMultipleAsync(2, connection, transaction, (dr, result) => + { + switch (result) + { + case 0: + if (indexes1 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag1 = sbflag.ToString(); + } + ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); + break; + case 1: + if (indexes2 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag2 = sbflag.ToString(); + } + ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); + break; + } + return Task.FromResult(false); + }, cmdType, cmdText, cmdParms); + return (ret1, ret2); + } - public Task<(List, List, List)> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); - public Task<(List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task<(List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List()); - var ret1 = new List(); - var type1 = typeof(T1); - string flag1 = null; - int[] indexes1 = null; - var props1 = GetQueryTypeProperties(type1); + public Task<(List, List, List)> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); + public Task<(List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task<(List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List()); + var ret1 = new List(); + var type1 = typeof(T1); + string flag1 = null; + int[] indexes1 = null; + var props1 = GetQueryTypeProperties(type1); - var ret2 = new List(); - var type2 = typeof(T2); - string flag2 = null; - int[] indexes2 = null; - var props2 = GetQueryTypeProperties(type2); + var ret2 = new List(); + var type2 = typeof(T2); + string flag2 = null; + int[] indexes2 = null; + var props2 = GetQueryTypeProperties(type2); - var ret3 = new List(); - var type3 = typeof(T3); - string flag3 = null; - int[] indexes3 = null; - var props3 = GetQueryTypeProperties(type3); - await ExecuteReaderMultipleAsync(3, connection, transaction, (dr, result) => { - switch (result) { - case 0: - if (indexes1 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag1 = sbflag.ToString(); - } - ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); - break; - case 1: - if (indexes2 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag2 = sbflag.ToString(); - } - ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); - break; - case 2: - if (indexes3 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag3 = sbflag.ToString(); - } - ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); - break; - } - return Task.FromResult(false); - }, cmdType, cmdText, cmdParms); - return (ret1, ret2, ret3); - } + var ret3 = new List(); + var type3 = typeof(T3); + string flag3 = null; + int[] indexes3 = null; + var props3 = GetQueryTypeProperties(type3); + await ExecuteReaderMultipleAsync(3, connection, transaction, (dr, result) => + { + switch (result) + { + case 0: + if (indexes1 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag1 = sbflag.ToString(); + } + ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); + break; + case 1: + if (indexes2 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag2 = sbflag.ToString(); + } + ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); + break; + case 2: + if (indexes3 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag3 = sbflag.ToString(); + } + ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); + break; + } + return Task.FromResult(false); + }, cmdType, cmdText, cmdParms); + return (ret1, ret2, ret3); + } - public Task<(List, List, List, List)> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); - public Task<(List, List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task<(List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List(), new List()); - var ret1 = new List(); - var type1 = typeof(T1); - string flag1 = null; - int[] indexes1 = null; - var props1 = GetQueryTypeProperties(type1); + public Task<(List, List, List, List)> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); + public Task<(List, List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task<(List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List(), new List()); + var ret1 = new List(); + var type1 = typeof(T1); + string flag1 = null; + int[] indexes1 = null; + var props1 = GetQueryTypeProperties(type1); - var ret2 = new List(); - var type2 = typeof(T2); - string flag2 = null; - int[] indexes2 = null; - var props2 = GetQueryTypeProperties(type2); + var ret2 = new List(); + var type2 = typeof(T2); + string flag2 = null; + int[] indexes2 = null; + var props2 = GetQueryTypeProperties(type2); - var ret3 = new List(); - var type3 = typeof(T3); - string flag3 = null; - int[] indexes3 = null; - var props3 = GetQueryTypeProperties(type3); + var ret3 = new List(); + var type3 = typeof(T3); + string flag3 = null; + int[] indexes3 = null; + var props3 = GetQueryTypeProperties(type3); - var ret4 = new List(); - var type4 = typeof(T4); - string flag4 = null; - int[] indexes4 = null; - var props4 = GetQueryTypeProperties(type4); - await ExecuteReaderMultipleAsync(4, connection, transaction, (dr, result) => { - switch (result) { - case 0: - if (indexes1 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag1 = sbflag.ToString(); - } - ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); - break; - case 1: - if (indexes2 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag2 = sbflag.ToString(); - } - ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); - break; - case 2: - if (indexes3 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag3 = sbflag.ToString(); - } - ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); - break; - case 3: - if (indexes4 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes4 = props4.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag4 = sbflag.ToString(); - } - ret4.Add((T4)Utils.ExecuteArrayRowReadClassOrTuple(flag4, type4, indexes4, dr, 0, _util).Value); - break; - } - return Task.FromResult(false); - }, cmdType, cmdText, cmdParms); - return (ret1, ret2, ret3, ret4); - } + var ret4 = new List(); + var type4 = typeof(T4); + string flag4 = null; + int[] indexes4 = null; + var props4 = GetQueryTypeProperties(type4); + await ExecuteReaderMultipleAsync(4, connection, transaction, (dr, result) => + { + switch (result) + { + case 0: + if (indexes1 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag1 = sbflag.ToString(); + } + ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); + break; + case 1: + if (indexes2 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag2 = sbflag.ToString(); + } + ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); + break; + case 2: + if (indexes3 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag3 = sbflag.ToString(); + } + ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); + break; + case 3: + if (indexes4 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes4 = props4.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag4 = sbflag.ToString(); + } + ret4.Add((T4)Utils.ExecuteArrayRowReadClassOrTuple(flag4, type4, indexes4, dr, 0, _util).Value); + break; + } + return Task.FromResult(false); + }, cmdType, cmdText, cmdParms); + return (ret1, ret2, ret3, ret4); + } - public Task<(List, List, List, List, List)> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task<(List, List, List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); - public Task<(List, List, List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task<(List, List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List(), new List(), new List()); - var ret1 = new List(); - var type1 = typeof(T1); - string flag1 = null; - int[] indexes1 = null; - var props1 = GetQueryTypeProperties(type1); + public Task<(List, List, List, List, List)> QueryAsync(string cmdText, object parms = null) => QueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List, List, List)> QueryAsync(DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => QueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task<(List, List, List, List, List)> QueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, null, cmdType, cmdText, cmdParms); + public Task<(List, List, List, List, List)> QueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => QueryAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task<(List, List, List, List, List)> QueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return (new List(), new List(), new List(), new List(), new List()); + var ret1 = new List(); + var type1 = typeof(T1); + string flag1 = null; + int[] indexes1 = null; + var props1 = GetQueryTypeProperties(type1); - var ret2 = new List(); - var type2 = typeof(T2); - string flag2 = null; - int[] indexes2 = null; - var props2 = GetQueryTypeProperties(type2); + var ret2 = new List(); + var type2 = typeof(T2); + string flag2 = null; + int[] indexes2 = null; + var props2 = GetQueryTypeProperties(type2); - var ret3 = new List(); - var type3 = typeof(T3); - string flag3 = null; - int[] indexes3 = null; - var props3 = GetQueryTypeProperties(type3); + var ret3 = new List(); + var type3 = typeof(T3); + string flag3 = null; + int[] indexes3 = null; + var props3 = GetQueryTypeProperties(type3); - var ret4 = new List(); - var type4 = typeof(T4); - string flag4 = null; - int[] indexes4 = null; - var props4 = GetQueryTypeProperties(type4); + var ret4 = new List(); + var type4 = typeof(T4); + string flag4 = null; + int[] indexes4 = null; + var props4 = GetQueryTypeProperties(type4); - var ret5 = new List(); - var type5 = typeof(T5); - string flag5 = null; - int[] indexes5 = null; - var props5 = GetQueryTypeProperties(type5); - await ExecuteReaderMultipleAsync(5, connection, transaction, (dr, result) => { - switch (result) { - case 0: - if (indexes1 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag1 = sbflag.ToString(); - } - ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); - break; - case 1: - if (indexes2 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag2 = sbflag.ToString(); - } - ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); - break; - case 2: - if (indexes3 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag3 = sbflag.ToString(); - } - ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); - break; - case 3: - if (indexes4 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes4 = props4.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag4 = sbflag.ToString(); - } - ret4.Add((T4)Utils.ExecuteArrayRowReadClassOrTuple(flag4, type4, indexes4, dr, 0, _util).Value); - break; - case 4: - if (indexes5 == null) { - var sbflag = new StringBuilder().Append("QueryAsync"); - var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - for (var a = 0; a < dr.FieldCount; a++) { - var name = dr.GetName(a); - sbflag.Append(name).Append(":").Append(a).Append(","); - dic.Add(name, a); - } - indexes5 = props5.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); - flag5 = sbflag.ToString(); - } - ret5.Add((T5)Utils.ExecuteArrayRowReadClassOrTuple(flag5, type5, indexes5, dr, 0, _util).Value); - break; - } - return Task.FromResult(false); - }, cmdType, cmdText, cmdParms); - return (ret1, ret2, ret3, ret4, ret5); - } - #endregion + var ret5 = new List(); + var type5 = typeof(T5); + string flag5 = null; + int[] indexes5 = null; + var props5 = GetQueryTypeProperties(type5); + await ExecuteReaderMultipleAsync(5, connection, transaction, (dr, result) => + { + switch (result) + { + case 0: + if (indexes1 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes1 = props1.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag1 = sbflag.ToString(); + } + ret1.Add((T1)Utils.ExecuteArrayRowReadClassOrTuple(flag1, type1, indexes1, dr, 0, _util).Value); + break; + case 1: + if (indexes2 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes2 = props2.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag2 = sbflag.ToString(); + } + ret2.Add((T2)Utils.ExecuteArrayRowReadClassOrTuple(flag2, type2, indexes2, dr, 0, _util).Value); + break; + case 2: + if (indexes3 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes3 = props3.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag3 = sbflag.ToString(); + } + ret3.Add((T3)Utils.ExecuteArrayRowReadClassOrTuple(flag3, type3, indexes3, dr, 0, _util).Value); + break; + case 3: + if (indexes4 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes4 = props4.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag4 = sbflag.ToString(); + } + ret4.Add((T4)Utils.ExecuteArrayRowReadClassOrTuple(flag4, type4, indexes4, dr, 0, _util).Value); + break; + case 4: + if (indexes5 == null) + { + var sbflag = new StringBuilder().Append("QueryAsync"); + var dic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + for (var a = 0; a < dr.FieldCount; a++) + { + var name = dr.GetName(a); + sbflag.Append(name).Append(":").Append(a).Append(","); + dic.Add(name, a); + } + indexes5 = props5.Select(a => dic.TryGetValue(a.Key, out var tryint) ? tryint : -1).ToArray(); + flag5 = sbflag.ToString(); + } + ret5.Add((T5)Utils.ExecuteArrayRowReadClassOrTuple(flag5, type5, indexes5, dr, 0, _util).Value); + break; + } + return Task.FromResult(false); + }, cmdType, cmdText, cmdParms); + return (ret1, ret2, ret3, ret4, ret5); + } + #endregion - public Task ExecuteReaderAsync(Func readerHander, string cmdText, object parms = null) => ExecuteReaderAsync(null, null, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteReaderAsync(DbTransaction transaction, Func readerHander, string cmdText, object parms = null) => ExecuteReaderAsync(null, transaction, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, Func readerHander, string cmdText, object parms = null) => ExecuteReaderAsync(connection, transaction, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteReaderAsync(Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReaderAsync(null, null, readerHander, cmdType, cmdText, cmdParms); - public Task ExecuteReaderAsync(DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReaderAsync(null, transaction, readerHander, cmdType, cmdText, cmdParms); - public Task ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReaderMultipleAsync(1, connection, transaction, (dr, result) => readerHander(dr), cmdType, cmdText, cmdParms); - async Task ExecuteReaderMultipleAsync(int multipleResult, DbConnection connection, DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return; - var dt = DateTime.Now; - var logtxt = new StringBuilder(); - var logtxt_dt = DateTime.Now; - var pool = this.MasterPool; - var isSlave = false; + public Task ExecuteReaderAsync(Func readerHander, string cmdText, object parms = null) => ExecuteReaderAsync(null, null, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteReaderAsync(DbTransaction transaction, Func readerHander, string cmdText, object parms = null) => ExecuteReaderAsync(null, transaction, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, Func readerHander, string cmdText, object parms = null) => ExecuteReaderAsync(connection, transaction, readerHander, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteReaderAsync(Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReaderAsync(null, null, readerHander, cmdType, cmdText, cmdParms); + public Task ExecuteReaderAsync(DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReaderAsync(null, transaction, readerHander, cmdType, cmdText, cmdParms); + public Task ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteReaderMultipleAsync(1, connection, transaction, (dr, result) => readerHander(dr), cmdType, cmdText, cmdParms); + async Task ExecuteReaderMultipleAsync(int multipleResult, DbConnection connection, DbTransaction transaction, Func readerHander, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return; + var dt = DateTime.Now; + var logtxt = new StringBuilder(); + var logtxt_dt = DateTime.Now; + var pool = this.MasterPool; + var isSlave = false; - if (transaction == null && connection == null) { - //读写分离规则 - if (this.SlavePools.Any() && cmdText.StartsWith("SELECT ", StringComparison.CurrentCultureIgnoreCase)) { - var availables = slaveUnavailables == 0 ? - //查从库 - this.SlavePools : ( - //查主库 - slaveUnavailables == this.SlavePools.Count ? new List>() : - //查从库可用 - this.SlavePools.Where(sp => sp.IsAvailable).ToList()); - if (availables.Any()) { - isSlave = true; - pool = availables.Count == 1 ? this.SlavePools[0] : availables[slaveRandom.Next(availables.Count)]; - } - } - } + if (transaction == null && connection == null) + { + //读写分离规则 + if (this.SlavePools.Any() && cmdText.StartsWith("SELECT ", StringComparison.CurrentCultureIgnoreCase)) + { + var availables = slaveUnavailables == 0 ? + //查从库 + this.SlavePools : ( + //查主库 + slaveUnavailables == this.SlavePools.Count ? new List>() : + //查从库可用 + this.SlavePools.Where(sp => sp.IsAvailable).ToList()); + if (availables.Any()) + { + isSlave = true; + pool = availables.Count == 1 ? this.SlavePools[0] : availables[slaveRandom.Next(availables.Count)]; + } + } + } - Object conn = null; - var pc = await PrepareCommandAsync(connection, transaction, cmdType, cmdText, cmdParms, logtxt); - if (IsTracePerformance) logtxt.Append("PrepareCommandAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - Exception ex = null; - try { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - if (isSlave) { - //从库查询切换,恢复 - bool isSlaveFail = false; - try { - if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = await pool.GetAsync()).Value; - //if (slaveRandom.Next(100) % 2 == 0) throw new Exception("测试从库抛出异常"); - } catch { - isSlaveFail = true; - } - if (isSlaveFail) { - if (conn != null) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); - if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); - } - LoggerException(pool, pc, new Exception($"连接失败,准备切换其他可用服务器"), dt, logtxt, false); - pc.cmd.Parameters.Clear(); - await ExecuteReaderMultipleAsync(multipleResult, connection, transaction, readerHander, cmdType, cmdText, cmdParms); - return; - } - } else { - //主库查询 - if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = await pool.GetAsync()).Value; - } - if (IsTracePerformance) { - logtxt.Append("OpenAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - logtxt_dt = DateTime.Now; - } - using (var dr = await pc.cmd.ExecuteReaderAsync()) { - if (IsTracePerformance) logtxt.Append("ExecuteReaderAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - int resultIndex = 0; - while (true) { - while (true) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - bool isread = await dr.ReadAsync(); - if (IsTracePerformance) logtxt.Append(" dr.ReadAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - if (isread == false) break; + Object conn = null; + var pc = await PrepareCommandAsync(connection, transaction, cmdType, cmdText, cmdParms, logtxt); + if (IsTracePerformance) logtxt.Append("PrepareCommandAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + Exception ex = null; + try + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + if (isSlave) + { + //从库查询切换,恢复 + bool isSlaveFail = false; + try + { + if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = await pool.GetAsync()).Value; + //if (slaveRandom.Next(100) % 2 == 0) throw new Exception("测试从库抛出异常"); + } + catch + { + isSlaveFail = true; + } + if (isSlaveFail) + { + if (conn != null) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); + if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); + } + LoggerException(pool, pc, new Exception($"连接失败,准备切换其他可用服务器"), dt, logtxt, false); + pc.cmd.Parameters.Clear(); + await ExecuteReaderMultipleAsync(multipleResult, connection, transaction, readerHander, cmdType, cmdText, cmdParms); + return; + } + } + else + { + //主库查询 + if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = await pool.GetAsync()).Value; + } + if (IsTracePerformance) + { + logtxt.Append("OpenAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + logtxt_dt = DateTime.Now; + } + using (var dr = await pc.cmd.ExecuteReaderAsync()) + { + if (IsTracePerformance) logtxt.Append("ExecuteReaderAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + int resultIndex = 0; + while (true) + { + while (true) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + bool isread = await dr.ReadAsync(); + if (IsTracePerformance) logtxt.Append(" dr.ReadAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + if (isread == false) break; - if (readerHander != null) { - object[] values = null; - if (IsTracePerformance) { - logtxt_dt = DateTime.Now; - values = new object[dr.FieldCount]; - for (int a = 0; a < values.Length; a++) if (!await dr.IsDBNullAsync(a)) values[a] = await dr.GetFieldValueAsync(a); - logtxt.Append(" dr.GetValues: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - logtxt_dt = DateTime.Now; - } - await readerHander(dr, resultIndex); - if (IsTracePerformance) logtxt.Append(" readerHanderAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms (").Append(string.Join(", ", values)).Append(")\r\n"); - } - } - if (++resultIndex >= multipleResult || dr.NextResult() == false) break; - } - if (IsTracePerformance) logtxt_dt = DateTime.Now; - dr.Close(); - } - if (IsTracePerformance) logtxt.Append("ExecuteReaderAsync_dispose: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - } catch (Exception ex2) { - ex = ex2; - } + if (readerHander != null) + { + object[] values = null; + if (IsTracePerformance) + { + logtxt_dt = DateTime.Now; + values = new object[dr.FieldCount]; + for (int a = 0; a < values.Length; a++) if (!await dr.IsDBNullAsync(a)) values[a] = await dr.GetFieldValueAsync(a); + logtxt.Append(" dr.GetValues: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + logtxt_dt = DateTime.Now; + } + await readerHander(dr, resultIndex); + if (IsTracePerformance) logtxt.Append(" readerHanderAsync: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms (").Append(string.Join(", ", values)).Append(")\r\n"); + } + } + if (++resultIndex >= multipleResult || dr.NextResult() == false) break; + } + if (IsTracePerformance) logtxt_dt = DateTime.Now; + dr.Close(); + } + if (IsTracePerformance) logtxt.Append("ExecuteReaderAsync_dispose: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + } + catch (Exception ex2) + { + ex = ex2; + } - if (conn != null) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); - if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); - } - LoggerException(pool, pc, ex, dt, logtxt); - pc.cmd.Parameters.Clear(); - } - public Task ExecuteArrayAsync(string cmdText, object parms = null) => ExecuteArrayAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteArrayAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteArrayAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteArrayAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteArrayAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteArrayAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteArrayAsync(null, null, cmdType, cmdText, cmdParms); - public Task ExecuteArrayAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteArrayAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task ExecuteArrayAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - List ret = new List(); - await ExecuteReaderAsync(connection, transaction, async dr => { - object[] values = new object[dr.FieldCount]; - for (int a = 0; a < values.Length; a++) if (!await dr.IsDBNullAsync(a)) values[a] = await dr.GetFieldValueAsync(a); - ret.Add(values); - }, cmdType, cmdText, cmdParms); - return ret.ToArray(); - } + if (conn != null) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + ReturnConnection(pool, conn, ex); //pool.Return(conn, ex); + if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); + } + LoggerException(pool, pc, ex, dt, logtxt); + pc.cmd.Parameters.Clear(); + } + public Task ExecuteArrayAsync(string cmdText, object parms = null) => ExecuteArrayAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteArrayAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteArrayAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteArrayAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteArrayAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteArrayAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteArrayAsync(null, null, cmdType, cmdText, cmdParms); + public Task ExecuteArrayAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteArrayAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task ExecuteArrayAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + List ret = new List(); + await ExecuteReaderAsync(connection, transaction, async dr => + { + object[] values = new object[dr.FieldCount]; + for (int a = 0; a < values.Length; a++) if (!await dr.IsDBNullAsync(a)) values[a] = await dr.GetFieldValueAsync(a); + ret.Add(values); + }, cmdType, cmdText, cmdParms); + return ret.ToArray(); + } - public Task ExecuteDataSetAsync(string cmdText, object parms = null) => ExecuteDataSetAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteDataSetAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataSetAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteDataSetAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataSetAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteDataSetAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataSetAsync(null, null, cmdType, cmdText, cmdParms); - public Task ExecuteDataSetAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataSetAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task ExecuteDataSetAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - var ret = new DataSet(); - DataTable dt = null; - await ExecuteReaderMultipleAsync(16, connection, transaction, async (dr, result) => { - if (ret.Tables.Count <= result) { - dt = ret.Tables.Add(); - for (var a = 0; a < dr.FieldCount; a++) dt.Columns.Add(dr.GetName(a)); - } - object[] values = new object[dt.Columns.Count]; - for (int a = 0; a < values.Length; a++) if (!await dr.IsDBNullAsync(a)) values[a] = await dr.GetFieldValueAsync(a); - dt.Rows.Add(values); - }, cmdType, cmdText, cmdParms); - return ret; - } - public Task ExecuteDataTableAsync(string cmdText, object parms = null) => ExecuteDataTableAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteDataTableAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataTableAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteDataTableAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataTableAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteDataTableAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataTableAsync(null, null, cmdType, cmdText, cmdParms); - public Task ExecuteDataTableAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataTableAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task ExecuteDataTableAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - var ret = new DataTable(); - await ExecuteReaderAsync(connection, transaction, async dr => { - if (ret.Columns.Count == 0) - for (var a = 0; a < dr.FieldCount; a++) ret.Columns.Add(dr.GetName(a)); - object[] values = new object[ret.Columns.Count]; - for (int a = 0; a < values.Length; a++) if (!await dr.IsDBNullAsync(a)) values[a] = await dr.GetFieldValueAsync(a); - ret.Rows.Add(values); - }, cmdType, cmdText, cmdParms); - return ret; - } - public Task ExecuteNonQueryAsync(string cmdText, object parms = null) => ExecuteNonQueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteNonQueryAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteNonQueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteNonQueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteNonQueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteNonQueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteNonQueryAsync(null, null, cmdType, cmdText, cmdParms); - public Task ExecuteNonQueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteNonQueryAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task ExecuteNonQueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return 0; - var dt = DateTime.Now; - var logtxt = new StringBuilder(); - var logtxt_dt = DateTime.Now; - Object conn = null; - var pc = await PrepareCommandAsync(connection, transaction, cmdType, cmdText, cmdParms, logtxt); - int val = 0; - Exception ex = null; - try { - if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = await this.MasterPool.GetAsync()).Value; - val = await pc.cmd.ExecuteNonQueryAsync(); - } catch (Exception ex2) { - ex = ex2; - } + public Task ExecuteDataSetAsync(string cmdText, object parms = null) => ExecuteDataSetAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteDataSetAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataSetAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteDataSetAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataSetAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteDataSetAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataSetAsync(null, null, cmdType, cmdText, cmdParms); + public Task ExecuteDataSetAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataSetAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task ExecuteDataSetAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + var ret = new DataSet(); + DataTable dt = null; + await ExecuteReaderMultipleAsync(16, connection, transaction, async (dr, result) => + { + if (ret.Tables.Count <= result) + { + dt = ret.Tables.Add(); + for (var a = 0; a < dr.FieldCount; a++) dt.Columns.Add(dr.GetName(a)); + } + object[] values = new object[dt.Columns.Count]; + for (int a = 0; a < values.Length; a++) if (!await dr.IsDBNullAsync(a)) values[a] = await dr.GetFieldValueAsync(a); + dt.Rows.Add(values); + }, cmdType, cmdText, cmdParms); + return ret; + } + public Task ExecuteDataTableAsync(string cmdText, object parms = null) => ExecuteDataTableAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteDataTableAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataTableAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteDataTableAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteDataTableAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteDataTableAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataTableAsync(null, null, cmdType, cmdText, cmdParms); + public Task ExecuteDataTableAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteDataTableAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task ExecuteDataTableAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + var ret = new DataTable(); + await ExecuteReaderAsync(connection, transaction, async dr => + { + if (ret.Columns.Count == 0) + for (var a = 0; a < dr.FieldCount; a++) ret.Columns.Add(dr.GetName(a)); + object[] values = new object[ret.Columns.Count]; + for (int a = 0; a < values.Length; a++) if (!await dr.IsDBNullAsync(a)) values[a] = await dr.GetFieldValueAsync(a); + ret.Rows.Add(values); + }, cmdType, cmdText, cmdParms); + return ret; + } + public Task ExecuteNonQueryAsync(string cmdText, object parms = null) => ExecuteNonQueryAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteNonQueryAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteNonQueryAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteNonQueryAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteNonQueryAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteNonQueryAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteNonQueryAsync(null, null, cmdType, cmdText, cmdParms); + public Task ExecuteNonQueryAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteNonQueryAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task ExecuteNonQueryAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return 0; + var dt = DateTime.Now; + var logtxt = new StringBuilder(); + var logtxt_dt = DateTime.Now; + Object conn = null; + var pc = await PrepareCommandAsync(connection, transaction, cmdType, cmdText, cmdParms, logtxt); + int val = 0; + Exception ex = null; + try + { + if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = await this.MasterPool.GetAsync()).Value; + val = await pc.cmd.ExecuteNonQueryAsync(); + } + catch (Exception ex2) + { + ex = ex2; + } - if (conn != null) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - ReturnConnection(MasterPool, conn, ex); //this.MasterPool.Return(conn, ex); - if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); - } - LoggerException(this.MasterPool, pc, ex, dt, logtxt); - pc.cmd.Parameters.Clear(); - return val; - } - public Task ExecuteScalarAsync(string cmdText, object parms = null) => ExecuteScalarAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteScalarAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteScalarAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteScalarAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); - public Task ExecuteScalarAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteScalarAsync(null, null, cmdType, cmdText, cmdParms); - public Task ExecuteScalarAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteScalarAsync(null, transaction, cmdType, cmdText, cmdParms); - async public Task ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) { - if (string.IsNullOrEmpty(cmdText)) return null; - var dt = DateTime.Now; - var logtxt = new StringBuilder(); - var logtxt_dt = DateTime.Now; - Object conn = null; - var pc = await PrepareCommandAsync(connection, transaction, cmdType, cmdText, cmdParms, logtxt); - object val = null; - Exception ex = null; - try { - if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = await this.MasterPool.GetAsync()).Value; - val = await pc.cmd.ExecuteScalarAsync(); - } catch (Exception ex2) { - ex = ex2; - } + if (conn != null) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + ReturnConnection(MasterPool, conn, ex); //this.MasterPool.Return(conn, ex); + if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); + } + LoggerException(this.MasterPool, pc, ex, dt, logtxt); + pc.cmd.Parameters.Clear(); + return val; + } + public Task ExecuteScalarAsync(string cmdText, object parms = null) => ExecuteScalarAsync(null, null, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteScalarAsync(DbTransaction transaction, string cmdText, object parms = null) => ExecuteScalarAsync(null, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, string cmdText, object parms = null) => ExecuteScalarAsync(connection, transaction, CommandType.Text, cmdText, GetDbParamtersByObject(cmdText, parms)); + public Task ExecuteScalarAsync(CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteScalarAsync(null, null, cmdType, cmdText, cmdParms); + public Task ExecuteScalarAsync(DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) => ExecuteScalarAsync(null, transaction, cmdType, cmdText, cmdParms); + async public Task ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, params DbParameter[] cmdParms) + { + if (string.IsNullOrEmpty(cmdText)) return null; + var dt = DateTime.Now; + var logtxt = new StringBuilder(); + var logtxt_dt = DateTime.Now; + Object conn = null; + var pc = await PrepareCommandAsync(connection, transaction, cmdType, cmdText, cmdParms, logtxt); + object val = null; + Exception ex = null; + try + { + if (pc.cmd.Connection == null) pc.cmd.Connection = (conn = await this.MasterPool.GetAsync()).Value; + val = await pc.cmd.ExecuteScalarAsync(); + } + catch (Exception ex2) + { + ex = ex2; + } - if (conn != null) { - if (IsTracePerformance) logtxt_dt = DateTime.Now; - ReturnConnection(MasterPool, conn, ex); //this.MasterPool.Return(conn, ex); - if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); - } - LoggerException(this.MasterPool, pc, ex, dt, logtxt); - pc.cmd.Parameters.Clear(); - return val; - } + if (conn != null) + { + if (IsTracePerformance) logtxt_dt = DateTime.Now; + ReturnConnection(MasterPool, conn, ex); //this.MasterPool.Return(conn, ex); + if (IsTracePerformance) logtxt.Append("ReleaseConnection: ").Append(DateTime.Now.Subtract(logtxt_dt).TotalMilliseconds).Append("ms Total: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms"); + } + LoggerException(this.MasterPool, pc, ex, dt, logtxt); + pc.cmd.Parameters.Clear(); + return val; + } - async Task<(DbCommand cmd, bool isclose)> PrepareCommandAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, DbParameter[] cmdParms, StringBuilder logtxt) { - DateTime dt = DateTime.Now; - DbCommand cmd = CreateCommand(); - bool isclose = false; - cmd.CommandType = cmdType; - cmd.CommandText = cmdText; + async Task<(DbCommand cmd, bool isclose)> PrepareCommandAsync(DbConnection connection, DbTransaction transaction, CommandType cmdType, string cmdText, DbParameter[] cmdParms, StringBuilder logtxt) + { + DateTime dt = DateTime.Now; + DbCommand cmd = CreateCommand(); + bool isclose = false; + cmd.CommandType = cmdType; + cmd.CommandText = cmdText; - if (cmdParms != null) { - foreach (var parm in cmdParms) { - if (parm == null) continue; - if (parm.Value == null) parm.Value = DBNull.Value; - cmd.Parameters.Add(parm); - } - } + if (cmdParms != null) + { + foreach (var parm in cmdParms) + { + if (parm == null) continue; + if (parm.Value == null) parm.Value = DBNull.Value; + cmd.Parameters.Add(parm); + } + } - if (connection == null) { - var tran = transaction; + if (connection == null) + { + var tran = transaction; - if (tran != null) { - if (IsTracePerformance) dt = DateTime.Now; - cmd.Connection = tran.Connection; - cmd.Transaction = tran; - if (IsTracePerformance) logtxt.Append(" PrepareCommandAsync_tran!=null: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - } - } else { - if (connection.State != ConnectionState.Open) { - if (IsTracePerformance) dt = DateTime.Now; - await connection.OpenAsync(); - if (IsTracePerformance) logtxt.Append(" PrepareCommand_ConnectionOpenAsync: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); - isclose = true; - } - cmd.Connection = connection; - if (transaction?.Connection == connection) - cmd.Transaction = transaction; - } + if (tran != null) + { + if (IsTracePerformance) dt = DateTime.Now; + cmd.Connection = tran.Connection; + cmd.Transaction = tran; + if (IsTracePerformance) logtxt.Append(" PrepareCommandAsync_tran!=null: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + } + } + else + { + if (connection.State != ConnectionState.Open) + { + if (IsTracePerformance) dt = DateTime.Now; + await connection.OpenAsync(); + if (IsTracePerformance) logtxt.Append(" PrepareCommand_ConnectionOpenAsync: ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms\r\n"); + isclose = true; + } + cmd.Connection = connection; + if (transaction?.Connection == connection) + cmd.Transaction = transaction; + } - if (IsTracePerformance) logtxt.Append(" PrepareCommandAsync ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms cmdParms: ").Append(cmd.Parameters.Count).Append("\r\n"); + if (IsTracePerformance) logtxt.Append(" PrepareCommandAsync ").Append(DateTime.Now.Subtract(dt).TotalMilliseconds).Append("ms cmdParms: ").Append(cmd.Parameters.Count).Append("\r\n"); - AopCommandExecuting?.Invoke(cmd); - return (cmd, isclose); - } - } + AopCommandExecuting?.Invoke(cmd); + return (cmd, isclose); + } + } } diff --git a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderTransaction.cs b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderTransaction.cs index a6082fa9..9fb1b7c2 100644 --- a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderTransaction.cs +++ b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderTransaction.cs @@ -6,126 +6,158 @@ using System.Diagnostics; using System.Linq; using System.Threading; -namespace FreeSql.Internal.CommonProvider { - partial class AdoProvider { +namespace FreeSql.Internal.CommonProvider +{ + partial class AdoProvider + { - class Transaction2 { - internal Object Conn; - internal DbTransaction Transaction; - internal DateTime RunTime; - internal TimeSpan Timeout; + class Transaction2 + { + internal Object Conn; + internal DbTransaction Transaction; + internal DateTime RunTime; + internal TimeSpan Timeout; - public Transaction2(Object conn, DbTransaction tran, TimeSpan timeout) { - Conn = conn; - Transaction = tran; - RunTime = DateTime.Now; - Timeout = timeout; - } - } + public Transaction2(Object conn, DbTransaction tran, TimeSpan timeout) + { + Conn = conn; + Transaction = tran; + RunTime = DateTime.Now; + Timeout = timeout; + } + } - private Dictionary _trans = new Dictionary(); - private object _trans_lock = new object(); + private Dictionary _trans = new Dictionary(); + private object _trans_lock = new object(); - public DbTransaction TransactionCurrentThread => _trans.TryGetValue(Thread.CurrentThread.ManagedThreadId, out var conn) && conn.Transaction?.Connection != null ? conn.Transaction : null; + public DbTransaction TransactionCurrentThread => _trans.TryGetValue(Thread.CurrentThread.ManagedThreadId, out var conn) && conn.Transaction?.Connection != null ? conn.Transaction : null; - public void BeginTransaction(TimeSpan timeout) { - if (TransactionCurrentThread != null) return; + public void BeginTransaction(TimeSpan timeout) + { + if (TransactionCurrentThread != null) return; - int tid = Thread.CurrentThread.ManagedThreadId; - Transaction2 tran = null; - Object conn = null; + int tid = Thread.CurrentThread.ManagedThreadId; + Transaction2 tran = null; + Object conn = null; - try { - conn = MasterPool.Get(); - tran = new Transaction2(conn, conn.Value.BeginTransaction(), timeout); - } catch(Exception ex) { - Trace.WriteLine($"数据库出错(开启事务){ex.Message} \r\n{ex.StackTrace}"); - MasterPool.Return(conn); - throw ex; - } - if (_trans.ContainsKey(tid)) CommitTransaction(); + try + { + conn = MasterPool.Get(); + tran = new Transaction2(conn, conn.Value.BeginTransaction(), timeout); + } + catch (Exception ex) + { + Trace.WriteLine($"数据库出错(开启事务){ex.Message} \r\n{ex.StackTrace}"); + MasterPool.Return(conn); + throw ex; + } + if (_trans.ContainsKey(tid)) CommitTransaction(); - lock (_trans_lock) - _trans.Add(tid, tran); - } + lock (_trans_lock) + _trans.Add(tid, tran); + } - private void AutoCommitTransaction() { - if (_trans.Count > 0) { - Transaction2[] trans = null; - lock (_trans_lock) - trans = _trans.Values.Where(st2 => DateTime.Now.Subtract(st2.RunTime) > st2.Timeout).ToArray(); - foreach (Transaction2 tran in trans) CommitTransaction(true, tran); - } - } - private void CommitTransaction(bool isCommit, Transaction2 tran) { - if (tran == null || tran.Transaction == null || tran.Transaction.Connection == null) return; + private void AutoCommitTransaction() + { + if (_trans.Count > 0) + { + Transaction2[] trans = null; + lock (_trans_lock) + trans = _trans.Values.Where(st2 => DateTime.Now.Subtract(st2.RunTime) > st2.Timeout).ToArray(); + foreach (Transaction2 tran in trans) CommitTransaction(true, tran); + } + } + private void CommitTransaction(bool isCommit, Transaction2 tran) + { + if (tran == null || tran.Transaction == null || tran.Transaction.Connection == null) return; - if (_trans.ContainsKey(tran.Conn.LastGetThreadId)) - lock (_trans_lock) - if (_trans.ContainsKey(tran.Conn.LastGetThreadId)) - _trans.Remove(tran.Conn.LastGetThreadId); + if (_trans.ContainsKey(tran.Conn.LastGetThreadId)) + lock (_trans_lock) + if (_trans.ContainsKey(tran.Conn.LastGetThreadId)) + _trans.Remove(tran.Conn.LastGetThreadId); - Exception ex = null; - var f001 = isCommit ? "提交" : "回滚"; - try { - Trace.WriteLine($"线程{tran.Conn.LastGetThreadId}事务{f001}"); - if (isCommit) tran.Transaction.Commit(); - else tran.Transaction.Rollback(); - } catch (Exception ex2) { - ex = ex2; - Trace.WriteLine($"数据库出错({f001}事务):{ex.Message} {ex.StackTrace}"); - } finally { - ReturnConnection(MasterPool, tran.Conn, ex); //MasterPool.Return(tran.Conn, ex); - } - } - private void CommitTransaction(bool isCommit) { - if (_trans.TryGetValue(Thread.CurrentThread.ManagedThreadId, out var tran)) CommitTransaction(isCommit, tran); - } - public void CommitTransaction() => CommitTransaction(true); - public void RollbackTransaction() => CommitTransaction(false); + Exception ex = null; + var f001 = isCommit ? "提交" : "回滚"; + try + { + Trace.WriteLine($"线程{tran.Conn.LastGetThreadId}事务{f001}"); + if (isCommit) tran.Transaction.Commit(); + else tran.Transaction.Rollback(); + } + catch (Exception ex2) + { + ex = ex2; + Trace.WriteLine($"数据库出错({f001}事务):{ex.Message} {ex.StackTrace}"); + } + finally + { + ReturnConnection(MasterPool, tran.Conn, ex); //MasterPool.Return(tran.Conn, ex); + } + } + private void CommitTransaction(bool isCommit) + { + if (_trans.TryGetValue(Thread.CurrentThread.ManagedThreadId, out var tran)) CommitTransaction(isCommit, tran); + } + public void CommitTransaction() => CommitTransaction(true); + public void RollbackTransaction() => CommitTransaction(false); - public void Transaction(Action handler) { - Transaction(handler, TimeSpan.FromSeconds(60)); - } - public void Transaction(Action handler, TimeSpan timeout) { - try { - BeginTransaction(timeout); - handler(); - CommitTransaction(); - } catch (Exception ex) { - RollbackTransaction(); - throw ex; - } - } + public void Transaction(Action handler) + { + Transaction(handler, TimeSpan.FromSeconds(60)); + } + public void Transaction(Action handler, TimeSpan timeout) + { + try + { + BeginTransaction(timeout); + handler(); + CommitTransaction(); + } + catch (Exception ex) + { + RollbackTransaction(); + throw ex; + } + } - ~AdoProvider() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - try { - Transaction2[] trans = null; - lock (_trans_lock) - trans = _trans.Values.ToArray(); - foreach (Transaction2 tran in trans) CommitTransaction(false, tran); - } catch { } + ~AdoProvider() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + try + { + Transaction2[] trans = null; + lock (_trans_lock) + trans = _trans.Values.ToArray(); + foreach (Transaction2 tran in trans) CommitTransaction(false, tran); + } + catch { } - ObjectPool[] pools = null; - for (var a = 0; a < 10; a++) { - try { - pools = SlavePools.ToArray(); - SlavePools.Clear(); - break; - } catch { - } - } - if (pools != null) { - foreach (var pool in pools) { - try { pool.Dispose(); } catch { } - } - } - try { MasterPool.Dispose(); } catch { } - } - } + ObjectPool[] pools = null; + for (var a = 0; a < 10; a++) + { + try + { + pools = SlavePools.ToArray(); + SlavePools.Clear(); + break; + } + catch + { + } + } + if (pools != null) + { + foreach (var pool in pools) + { + try { pool.Dispose(); } catch { } + } + } + try { MasterPool.Dispose(); } catch { } + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderUtils.cs b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderUtils.cs index c9b7311e..4d5aae64 100644 --- a/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderUtils.cs +++ b/FreeSql/Internal/CommonProvider/AdoProvider/AdoProviderUtils.cs @@ -2,21 +2,25 @@ using System.Collections.Concurrent; using System.Text.RegularExpressions; -namespace FreeSql.Internal.CommonProvider { - partial class AdoProvider { - public abstract object AddslashesProcessParam(object param, Type mapType); - public string Addslashes(string filter, params object[] parms) { - if (filter == null || parms == null) return string.Empty; - if (parms.Length == 0) return filter; - var nparms = new object[parms.Length]; - for (int a = 0; a < parms.Length; a++) { - if (parms[a] == null) - filter = _dicAddslashesReplaceIsNull.GetOrAdd(a, b => new Regex(@"\s*(=|IN)\s*\{" + b + @"\}", RegexOptions.IgnoreCase | RegexOptions.Compiled)) - .Replace(filter, $" IS {{{a}}}"); - nparms[a] = AddslashesProcessParam(parms[a], null); - } - try { string ret = string.Format(filter, nparms); return ret; } catch { return filter; } - } - static ConcurrentDictionary _dicAddslashesReplaceIsNull = new ConcurrentDictionary(); - } +namespace FreeSql.Internal.CommonProvider +{ + partial class AdoProvider + { + public abstract object AddslashesProcessParam(object param, Type mapType); + public string Addslashes(string filter, params object[] parms) + { + if (filter == null || parms == null) return string.Empty; + if (parms.Length == 0) return filter; + var nparms = new object[parms.Length]; + for (int a = 0; a < parms.Length; a++) + { + if (parms[a] == null) + filter = _dicAddslashesReplaceIsNull.GetOrAdd(a, b => new Regex(@"\s*(=|IN)\s*\{" + b + @"\}", RegexOptions.IgnoreCase | RegexOptions.Compiled)) + .Replace(filter, $" IS {{{a}}}"); + nparms[a] = AddslashesProcessParam(parms[a], null); + } + try { string ret = string.Format(filter, nparms); return ret; } catch { return filter; } + } + static ConcurrentDictionary _dicAddslashesReplaceIsNull = new ConcurrentDictionary(); + } } diff --git a/FreeSql/Internal/CommonProvider/AopProvider.cs b/FreeSql/Internal/CommonProvider/AopProvider.cs index bf49f3ba..3f6d15b2 100644 --- a/FreeSql/Internal/CommonProvider/AopProvider.cs +++ b/FreeSql/Internal/CommonProvider/AopProvider.cs @@ -4,16 +4,18 @@ using System.Collections.Generic; using System.Linq.Expressions; using System.Text; -namespace FreeSql.Internal.CommonProvider { - public class AopProvider : IAop { - public EventHandler ToList { get; set; } - public EventHandler Where { get; set; } - public EventHandler ParseExpression { get; set; } - public EventHandler ConfigEntity { get; set; } - public EventHandler ConfigEntityProperty { get; set; } - public EventHandler CurdBefore { get; set; } - public EventHandler CurdAfter { get; set; } - public EventHandler SyncStructureBefore { get; set; } - public EventHandler SyncStructureAfter { get; set; } - } +namespace FreeSql.Internal.CommonProvider +{ + public class AopProvider : IAop + { + public EventHandler ToList { get; set; } + public EventHandler Where { get; set; } + public EventHandler ParseExpression { get; set; } + public EventHandler ConfigEntity { get; set; } + public EventHandler ConfigEntityProperty { get; set; } + public EventHandler CurdBefore { get; set; } + public EventHandler CurdAfter { get; set; } + public EventHandler SyncStructureBefore { get; set; } + public EventHandler SyncStructureAfter { get; set; } + } } diff --git a/FreeSql/Internal/CommonProvider/CodeFirstProvider.cs b/FreeSql/Internal/CommonProvider/CodeFirstProvider.cs index 6f611883..e7edfceb 100644 --- a/FreeSql/Internal/CommonProvider/CodeFirstProvider.cs +++ b/FreeSql/Internal/CommonProvider/CodeFirstProvider.cs @@ -11,65 +11,76 @@ using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract partial class CodeFirstProvider : ICodeFirst { + public abstract partial class CodeFirstProvider : ICodeFirst + { - protected IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - public CodeFirstProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - } + protected IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + public CodeFirstProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + } - public bool IsAutoSyncStructure { get; set; } = false; - public bool IsSyncStructureToLower { get; set; } = false; - public bool IsSyncStructureToUpper { get; set; } = false; - public bool IsConfigEntityFromDbFirst { get; set; } = false; - public bool IsNoneCommandParameter { get; set; } = false; - public bool IsLazyLoading { get; set; } = false; + public bool IsAutoSyncStructure { get; set; } = false; + public bool IsSyncStructureToLower { get; set; } = false; + public bool IsSyncStructureToUpper { get; set; } = false; + public bool IsConfigEntityFromDbFirst { get; set; } = false; + public bool IsNoneCommandParameter { get; set; } = false; + public bool IsLazyLoading { get; set; } = false; - public abstract (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type); + public abstract (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type); - public ICodeFirst ConfigEntity(Action> entity) => _commonUtils.ConfigEntity(entity); - public ICodeFirst ConfigEntity(Type type, Action entity) => _commonUtils.ConfigEntity(type, entity); - public TableAttribute GetConfigEntity(Type type) => _commonUtils.GetConfigEntity(type); - public TableInfo GetTableByEntity(Type type) => _commonUtils.GetTableByEntity(type); + public ICodeFirst ConfigEntity(Action> entity) => _commonUtils.ConfigEntity(entity); + public ICodeFirst ConfigEntity(Type type, Action entity) => _commonUtils.ConfigEntity(type, entity); + public TableAttribute GetConfigEntity(Type type) => _commonUtils.GetConfigEntity(type); + public TableInfo GetTableByEntity(Type type) => _commonUtils.GetTableByEntity(type); - public string GetComparisonDDLStatements() => this.GetComparisonDDLStatements(typeof(TEntity)); - public abstract string GetComparisonDDLStatements(params Type[] entityTypes); + public string GetComparisonDDLStatements() => this.GetComparisonDDLStatements(typeof(TEntity)); + public abstract string GetComparisonDDLStatements(params Type[] entityTypes); - static object syncStructureLock = new object(); - internal ConcurrentDictionary dicSyced = new ConcurrentDictionary(); - public bool SyncStructure() => this.SyncStructure(typeof(TEntity)); - public bool SyncStructure(params Type[] entityTypes) { - if (entityTypes == null) return false; - var syncTypes = entityTypes.Where(a => dicSyced.ContainsKey(a.FullName) == false && GetTableByEntity(a)?.DisableSyncStructure == false).ToArray(); - if (syncTypes.Any() == false) return false; - var before = new Aop.SyncStructureBeforeEventArgs(entityTypes); - _orm.Aop.SyncStructureBefore?.Invoke(this, before); - Exception exception = null; - string ddl = null; - try { - lock (syncStructureLock) { - ddl = this.GetComparisonDDLStatements(syncTypes); - if (string.IsNullOrEmpty(ddl)) { - foreach (var syncType in syncTypes) dicSyced.TryAdd(syncType.FullName, true); - return true; - } - var affrows = _orm.Ado.ExecuteNonQuery(CommandType.Text, ddl); - foreach (var syncType in syncTypes) dicSyced.TryAdd(syncType.FullName, true); - return affrows > 0; - } - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.SyncStructureAfterEventArgs(before, ddl, exception); - _orm.Aop.SyncStructureAfter?.Invoke(this, after); - } - } - } + static object syncStructureLock = new object(); + internal ConcurrentDictionary dicSyced = new ConcurrentDictionary(); + public bool SyncStructure() => this.SyncStructure(typeof(TEntity)); + public bool SyncStructure(params Type[] entityTypes) + { + if (entityTypes == null) return false; + var syncTypes = entityTypes.Where(a => dicSyced.ContainsKey(a.FullName) == false && GetTableByEntity(a)?.DisableSyncStructure == false).ToArray(); + if (syncTypes.Any() == false) return false; + var before = new Aop.SyncStructureBeforeEventArgs(entityTypes); + _orm.Aop.SyncStructureBefore?.Invoke(this, before); + Exception exception = null; + string ddl = null; + try + { + lock (syncStructureLock) + { + ddl = this.GetComparisonDDLStatements(syncTypes); + if (string.IsNullOrEmpty(ddl)) + { + foreach (var syncType in syncTypes) dicSyced.TryAdd(syncType.FullName, true); + return true; + } + var affrows = _orm.Ado.ExecuteNonQuery(CommandType.Text, ddl); + foreach (var syncType in syncTypes) dicSyced.TryAdd(syncType.FullName, true); + return affrows > 0; + } + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.SyncStructureAfterEventArgs(before, ddl, exception); + _orm.Aop.SyncStructureAfter?.Invoke(this, after); + } + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/DeleteProvider.cs b/FreeSql/Internal/CommonProvider/DeleteProvider.cs index 43753aa4..e21168c1 100644 --- a/FreeSql/Internal/CommonProvider/DeleteProvider.cs +++ b/FreeSql/Internal/CommonProvider/DeleteProvider.cs @@ -7,119 +7,140 @@ using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract partial class DeleteProvider : IDelete where T1 : class { - protected IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - protected TableInfo _table; - protected Func _tableRule; - protected StringBuilder _where = new StringBuilder(); - protected int _whereTimes = 0; - protected List _params = new List(); - protected DbTransaction _transaction; - protected DbConnection _connection; + public abstract partial class DeleteProvider : IDelete where T1 : class + { + protected IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + protected TableInfo _table; + protected Func _tableRule; + protected StringBuilder _where = new StringBuilder(); + protected int _whereTimes = 0; + protected List _params = new List(); + protected DbTransaction _transaction; + protected DbConnection _connection; - public DeleteProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - _table = _commonUtils.GetTableByEntity(typeof(T1)); - this.Where(_commonUtils.WhereObject(_table, "", dywhere)); - if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); - } + public DeleteProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + _table = _commonUtils.GetTableByEntity(typeof(T1)); + this.Where(_commonUtils.WhereObject(_table, "", dywhere)); + if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); + } - protected void ClearData() { - _where.Clear(); - _whereTimes = 0; - _params.Clear(); - } + protected void ClearData() + { + _where.Clear(); + _whereTimes = 0; + _params.Clear(); + } - public IDelete WithTransaction(DbTransaction transaction) { - _transaction = transaction; - _connection = _transaction?.Connection; - return this; - } - public IDelete WithConnection(DbConnection connection) { - if (_transaction?.Connection != connection) _transaction = null; - _connection = connection; - return this; - } + public IDelete WithTransaction(DbTransaction transaction) + { + _transaction = transaction; + _connection = _transaction?.Connection; + return this; + } + public IDelete WithConnection(DbConnection connection) + { + if (_transaction?.Connection != connection) _transaction = null; + _connection = connection; + return this; + } - public int ExecuteAffrows() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var affrows = 0; - Exception exception = null; - try { - affrows = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, affrows); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return affrows; - } - async public Task ExecuteAffrowsAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var affrows = 0; - Exception exception = null; - try { - affrows = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, affrows); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return affrows; - } - public abstract List ExecuteDeleted(); - public abstract Task> ExecuteDeletedAsync(); + public int ExecuteAffrows() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var affrows = 0; + Exception exception = null; + try + { + affrows = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, affrows); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return affrows; + } + async public Task ExecuteAffrowsAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var affrows = 0; + Exception exception = null; + try + { + affrows = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, affrows); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return affrows; + } + public abstract List ExecuteDeleted(); + public abstract Task> ExecuteDeletedAsync(); - public IDelete Where(Expression> exp) => this.Where(_commonExpression.ExpressionWhereLambdaNoneForeignObject(null, _table, null, exp?.Body, null)); - public IDelete Where(string sql, object parms = null) { - if (string.IsNullOrEmpty(sql)) return this; - var args = new Aop.WhereEventArgs(sql, parms); - _orm.Aop.Where?.Invoke(this, new Aop.WhereEventArgs(sql, parms)); - if (args.IsCancel == true) return this; + public IDelete Where(Expression> exp) => this.Where(_commonExpression.ExpressionWhereLambdaNoneForeignObject(null, _table, null, exp?.Body, null)); + public IDelete Where(string sql, object parms = null) + { + if (string.IsNullOrEmpty(sql)) return this; + var args = new Aop.WhereEventArgs(sql, parms); + _orm.Aop.Where?.Invoke(this, new Aop.WhereEventArgs(sql, parms)); + if (args.IsCancel == true) return this; - if (++_whereTimes > 1) _where.Append(" AND "); - _where.Append("(").Append(sql).Append(")"); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this; - } - public IDelete Where(T1 item) => this.Where(new[] { item }); - public IDelete Where(IEnumerable items) => this.Where(_commonUtils.WhereItems(_table, "", items)); - public IDelete WhereExists(ISelect select, bool notExists = false) where TEntity2 : class => this.Where($"{(notExists ? "NOT " : "")}EXISTS({select.ToSql("1")})"); - public IDelete WhereDynamic(object dywhere) => this.Where(_commonUtils.WhereObject(_table, "", dywhere)); + if (++_whereTimes > 1) _where.Append(" AND "); + _where.Append("(").Append(sql).Append(")"); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this; + } + public IDelete Where(T1 item) => this.Where(new[] { item }); + public IDelete Where(IEnumerable items) => this.Where(_commonUtils.WhereItems(_table, "", items)); + public IDelete WhereExists(ISelect select, bool notExists = false) where TEntity2 : class => this.Where($"{(notExists ? "NOT " : "")}EXISTS({select.ToSql("1")})"); + public IDelete WhereDynamic(object dywhere) => this.Where(_commonUtils.WhereObject(_table, "", dywhere)); - public IDelete AsTable(Func tableRule) { - _tableRule = tableRule; - return this; - } - public IDelete AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("IDelete.AsType 参数不支持指定为 object"); - if (entityType == _table.Type) return this; - var newtb = _commonUtils.GetTableByEntity(entityType); - _table = newtb ?? throw new Exception("IDelete.AsType 参数错误,请传入正确的实体类型"); - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); - return this; - } + public IDelete AsTable(Func tableRule) + { + _tableRule = tableRule; + return this; + } + public IDelete AsType(Type entityType) + { + if (entityType == typeof(object)) throw new Exception("IDelete.AsType 参数不支持指定为 object"); + if (entityType == _table.Type) return this; + var newtb = _commonUtils.GetTableByEntity(entityType); + _table = newtb ?? throw new Exception("IDelete.AsType 参数错误,请传入正确的实体类型"); + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); + return this; + } - public string ToSql() => _whereTimes <= 0 ? null : new StringBuilder().Append("DELETE FROM ").Append(_commonUtils.QuoteSqlName(_tableRule?.Invoke(_table.DbName) ?? _table.DbName)).Append(" WHERE ").Append(_where).ToString(); - } + public string ToSql() => _whereTimes <= 0 ? null : new StringBuilder().Append("DELETE FROM ").Append(_commonUtils.QuoteSqlName(_tableRule?.Invoke(_table.DbName) ?? _table.DbName)).Append(" WHERE ").Append(_where).ToString(); + } } diff --git a/FreeSql/Internal/CommonProvider/InsertProvider.cs b/FreeSql/Internal/CommonProvider/InsertProvider.cs index 9ebdc0ed..f3363db3 100644 --- a/FreeSql/Internal/CommonProvider/InsertProvider.cs +++ b/FreeSql/Internal/CommonProvider/InsertProvider.cs @@ -9,436 +9,545 @@ using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract partial class InsertProvider : IInsert where T1 : class { - protected IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - protected List _source = new List(); - protected Dictionary _ignore = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - protected TableInfo _table; - protected Func _tableRule; - protected bool _noneParameter; - protected DbParameter[] _params; - protected DbTransaction _transaction; - protected DbConnection _connection; + public abstract partial class InsertProvider : IInsert where T1 : class + { + protected IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + protected List _source = new List(); + protected Dictionary _ignore = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + protected TableInfo _table; + protected Func _tableRule; + protected bool _noneParameter; + protected DbParameter[] _params; + protected DbTransaction _transaction; + protected DbConnection _connection; - public InsertProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - _table = _commonUtils.GetTableByEntity(typeof(T1)); - _noneParameter = _orm.CodeFirst.IsNoneCommandParameter; - if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); - } + public InsertProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + _table = _commonUtils.GetTableByEntity(typeof(T1)); + _noneParameter = _orm.CodeFirst.IsNoneCommandParameter; + if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); + } - protected void ClearData() { - _source.Clear(); - _ignore.Clear(); - _params = null; - } + protected void ClearData() + { + _source.Clear(); + _ignore.Clear(); + _params = null; + } - public IInsert WithTransaction(DbTransaction transaction) { - _transaction = transaction; - _connection = _transaction?.Connection; - return this; - } - public IInsert WithConnection(DbConnection connection) { - if (_transaction?.Connection != connection) _transaction = null; - _connection = connection; - return this; - } + public IInsert WithTransaction(DbTransaction transaction) + { + _transaction = transaction; + _connection = _transaction?.Connection; + return this; + } + public IInsert WithConnection(DbConnection connection) + { + if (_transaction?.Connection != connection) _transaction = null; + _connection = connection; + return this; + } - public IInsert NoneParameter() { - _noneParameter = true; - return this; - } + public IInsert NoneParameter() + { + _noneParameter = true; + return this; + } - public IInsert AppendData(T1 source) { - if (source != null) _source.Add(source); - return this; - } - public IInsert AppendData(T1[] source) { - if (source != null) _source.AddRange(source); - return this; - } - public IInsert AppendData(IEnumerable source) { - if (source != null) _source.AddRange(source.Where(a => a != null)); - return this; - } + public IInsert AppendData(T1 source) + { + if (source != null) _source.Add(source); + return this; + } + public IInsert AppendData(T1[] source) + { + if (source != null) _source.AddRange(source); + return this; + } + public IInsert AppendData(IEnumerable source) + { + if (source != null) _source.AddRange(source.Where(a => a != null)); + return this; + } - #region 参数化数据限制,或values数量限制 - protected List[] SplitSource(int valuesLimit, int parameterLimit) { - valuesLimit = valuesLimit - 1; - parameterLimit = parameterLimit - 1; - if (_source == null || _source.Any() == false) return new List[0]; - if (_source.Count == 1) return new[] { _source }; - if (_noneParameter) { - if (_source.Count < valuesLimit) return new[] { _source }; + #region 参数化数据限制,或values数量限制 + protected List[] SplitSource(int valuesLimit, int parameterLimit) + { + valuesLimit = valuesLimit - 1; + parameterLimit = parameterLimit - 1; + if (_source == null || _source.Any() == false) return new List[0]; + if (_source.Count == 1) return new[] { _source }; + if (_noneParameter) + { + if (_source.Count < valuesLimit) return new[] { _source }; - var execCount = (int)Math.Ceiling(1.0 * _source.Count / valuesLimit); - var ret = new List[execCount]; - for (var a = 0; a < execCount; a++) { - var subSource = new List(); - subSource = _source.GetRange(a * valuesLimit, Math.Min(valuesLimit, _source.Count - a * valuesLimit)); - ret[a] = subSource; - } - return ret; - } else { - var colSum = _table.Columns.Count - _ignore.Count; - var takeMax = parameterLimit / colSum; - var pamTotal = colSum * _source.Count; - if (pamTotal < parameterLimit) return new[] { _source }; + var execCount = (int)Math.Ceiling(1.0 * _source.Count / valuesLimit); + var ret = new List[execCount]; + for (var a = 0; a < execCount; a++) + { + var subSource = new List(); + subSource = _source.GetRange(a * valuesLimit, Math.Min(valuesLimit, _source.Count - a * valuesLimit)); + ret[a] = subSource; + } + return ret; + } + else + { + var colSum = _table.Columns.Count - _ignore.Count; + var takeMax = parameterLimit / colSum; + var pamTotal = colSum * _source.Count; + if (pamTotal < parameterLimit) return new[] { _source }; - var execCount = (int)Math.Ceiling(1.0 * pamTotal / takeMax / colSum); - var ret = new List[execCount]; - for (var a = 0; a < execCount; a++) { - var subSource = new List(); - subSource = _source.GetRange(a * takeMax, Math.Min(takeMax, _source.Count - a * takeMax)); - ret[a] = subSource; - } - return ret; - } - } - protected int SplitExecuteAffrows(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - var ret = 0; - if (ss.Any() == false) { - ClearData(); - return ret; - } - if (ss.Length == 1) { - ret = this.RawExecuteAffrows(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret += this.RawExecuteAffrows(); - } - } else { - using (var conn = _orm.Ado.MasterPool.Get()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret += this.RawExecuteAffrows(); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - async protected Task SplitExecuteAffrowsAsync(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - var ret = 0; - if (ss.Any() == false) { - ClearData(); - return ret; - } - if (ss.Length == 1) { - ret = await this.RawExecuteAffrowsAsync(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret += await this.RawExecuteAffrowsAsync(); - } - } else { - using (var conn = await _orm.Ado.MasterPool.GetAsync()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret += await this.RawExecuteAffrowsAsync(); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - protected long SplitExecuteIdentity(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - long ret = 0; - if (ss.Any() == false) { - ClearData(); - return ret; - } - if (ss.Length == 1) { - ret = this.RawExecuteIdentity(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - if (a < ss.Length - 1) this.RawExecuteAffrows(); - else ret = this.RawExecuteIdentity(); - } - } else { - using (var conn = _orm.Ado.MasterPool.Get()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - if (a < ss.Length - 1) this.RawExecuteAffrows(); - else ret = this.RawExecuteIdentity(); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - async protected Task SplitExecuteIdentityAsync(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - long ret = 0; - if (ss.Any() == false) { - ClearData(); - return ret; - } - if (ss.Length == 1) { - ret = await this.RawExecuteIdentityAsync(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - if (a < ss.Length - 1) await this.RawExecuteAffrowsAsync(); - else ret = await this.RawExecuteIdentityAsync(); - } - } else { - using (var conn = await _orm.Ado.MasterPool.GetAsync()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - if (a < ss.Length - 1) await this.RawExecuteAffrowsAsync(); - else ret = await this.RawExecuteIdentityAsync(); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - protected List SplitExecuteInserted(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - var ret = new List(); - if (ss.Any() == false) { - ClearData(); - return ret; - } - if (ss.Length == 1) { - ret = this.RawExecuteInserted(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret.AddRange(this.RawExecuteInserted()); - } - } else { - using (var conn = _orm.Ado.MasterPool.Get()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret.AddRange(this.RawExecuteInserted()); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - async protected Task> SplitExecuteInsertedAsync(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - var ret = new List(); - if (ss.Any() == false) { - ClearData(); - return ret; - } - if (ss.Length == 1) { - ret = await this.RawExecuteInsertedAsync(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret.AddRange(await this.RawExecuteInsertedAsync()); - } - } else { - using (var conn = await _orm.Ado.MasterPool.GetAsync()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret.AddRange(await this.RawExecuteInsertedAsync()); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - #endregion + var execCount = (int)Math.Ceiling(1.0 * pamTotal / takeMax / colSum); + var ret = new List[execCount]; + for (var a = 0; a < execCount; a++) + { + var subSource = new List(); + subSource = _source.GetRange(a * takeMax, Math.Min(takeMax, _source.Count - a * takeMax)); + ret[a] = subSource; + } + return ret; + } + } + protected int SplitExecuteAffrows(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + var ret = 0; + if (ss.Any() == false) + { + ClearData(); + return ret; + } + if (ss.Length == 1) + { + ret = this.RawExecuteAffrows(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret += this.RawExecuteAffrows(); + } + } + else + { + using (var conn = _orm.Ado.MasterPool.Get()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret += this.RawExecuteAffrows(); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + async protected Task SplitExecuteAffrowsAsync(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + var ret = 0; + if (ss.Any() == false) + { + ClearData(); + return ret; + } + if (ss.Length == 1) + { + ret = await this.RawExecuteAffrowsAsync(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret += await this.RawExecuteAffrowsAsync(); + } + } + else + { + using (var conn = await _orm.Ado.MasterPool.GetAsync()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret += await this.RawExecuteAffrowsAsync(); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + protected long SplitExecuteIdentity(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + long ret = 0; + if (ss.Any() == false) + { + ClearData(); + return ret; + } + if (ss.Length == 1) + { + ret = this.RawExecuteIdentity(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + if (a < ss.Length - 1) this.RawExecuteAffrows(); + else ret = this.RawExecuteIdentity(); + } + } + else + { + using (var conn = _orm.Ado.MasterPool.Get()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + if (a < ss.Length - 1) this.RawExecuteAffrows(); + else ret = this.RawExecuteIdentity(); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + async protected Task SplitExecuteIdentityAsync(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + long ret = 0; + if (ss.Any() == false) + { + ClearData(); + return ret; + } + if (ss.Length == 1) + { + ret = await this.RawExecuteIdentityAsync(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + if (a < ss.Length - 1) await this.RawExecuteAffrowsAsync(); + else ret = await this.RawExecuteIdentityAsync(); + } + } + else + { + using (var conn = await _orm.Ado.MasterPool.GetAsync()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + if (a < ss.Length - 1) await this.RawExecuteAffrowsAsync(); + else ret = await this.RawExecuteIdentityAsync(); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + protected List SplitExecuteInserted(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + var ret = new List(); + if (ss.Any() == false) + { + ClearData(); + return ret; + } + if (ss.Length == 1) + { + ret = this.RawExecuteInserted(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret.AddRange(this.RawExecuteInserted()); + } + } + else + { + using (var conn = _orm.Ado.MasterPool.Get()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret.AddRange(this.RawExecuteInserted()); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + async protected Task> SplitExecuteInsertedAsync(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + var ret = new List(); + if (ss.Any() == false) + { + ClearData(); + return ret; + } + if (ss.Length == 1) + { + ret = await this.RawExecuteInsertedAsync(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret.AddRange(await this.RawExecuteInsertedAsync()); + } + } + else + { + using (var conn = await _orm.Ado.MasterPool.GetAsync()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret.AddRange(await this.RawExecuteInsertedAsync()); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + #endregion - protected int RawExecuteAffrows() { - var sql = ToSql(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - var affrows = 0; - Exception exception = null; - try { - affrows = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, affrows); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return affrows; - } - async protected Task RawExecuteAffrowsAsync() { - var sql = ToSql(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - var affrows = 0; - Exception exception = null; - try { - affrows = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, affrows); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return affrows; - } - protected abstract long RawExecuteIdentity(); - protected abstract Task RawExecuteIdentityAsync(); - protected abstract List RawExecuteInserted(); - protected abstract Task> RawExecuteInsertedAsync(); + protected int RawExecuteAffrows() + { + var sql = ToSql(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + var affrows = 0; + Exception exception = null; + try + { + affrows = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, affrows); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return affrows; + } + async protected Task RawExecuteAffrowsAsync() + { + var sql = ToSql(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + var affrows = 0; + Exception exception = null; + try + { + affrows = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, affrows); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return affrows; + } + protected abstract long RawExecuteIdentity(); + protected abstract Task RawExecuteIdentityAsync(); + protected abstract List RawExecuteInserted(); + protected abstract Task> RawExecuteInsertedAsync(); - public abstract int ExecuteAffrows(); - public abstract Task ExecuteAffrowsAsync(); - public abstract long ExecuteIdentity(); - public abstract Task ExecuteIdentityAsync(); - public abstract List ExecuteInserted(); - public abstract Task> ExecuteInsertedAsync(); + public abstract int ExecuteAffrows(); + public abstract Task ExecuteAffrowsAsync(); + public abstract long ExecuteIdentity(); + public abstract Task ExecuteIdentityAsync(); + public abstract List ExecuteInserted(); + public abstract Task> ExecuteInsertedAsync(); - public IInsert IgnoreColumns(Expression> columns) { - var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, columns?.Body, false, null).Distinct(); - _ignore.Clear(); - foreach (var col in cols) _ignore.Add(col, true); - return this; - } - public IInsert InsertColumns(Expression> columns) { - var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, columns?.Body, false, null).ToDictionary(a => a, a => true); - _ignore.Clear(); - foreach (var col in _table.Columns.Values) - if (cols.ContainsKey(col.Attribute.Name) == false) - _ignore.Add(col.Attribute.Name, true); - return this; - } + public IInsert IgnoreColumns(Expression> columns) + { + var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, columns?.Body, false, null).Distinct(); + _ignore.Clear(); + foreach (var col in cols) _ignore.Add(col, true); + return this; + } + public IInsert InsertColumns(Expression> columns) + { + var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, columns?.Body, false, null).ToDictionary(a => a, a => true); + _ignore.Clear(); + foreach (var col in _table.Columns.Values) + if (cols.ContainsKey(col.Attribute.Name) == false) + _ignore.Add(col.Attribute.Name, true); + return this; + } - public IInsert AsTable(Func tableRule) { - _tableRule = tableRule; - return this; - } - public IInsert AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("IInsert.AsType 参数不支持指定为 object"); - if (entityType == _table.Type) return this; - var newtb = _commonUtils.GetTableByEntity(entityType); - _table = newtb ?? throw new Exception("IInsert.AsType 参数错误,请传入正确的实体类型"); - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); - return this; - } + public IInsert AsTable(Func tableRule) + { + _tableRule = tableRule; + return this; + } + public IInsert AsType(Type entityType) + { + if (entityType == typeof(object)) throw new Exception("IInsert.AsType 参数不支持指定为 object"); + if (entityType == _table.Type) return this; + var newtb = _commonUtils.GetTableByEntity(entityType); + _table = newtb ?? throw new Exception("IInsert.AsType 参数错误,请传入正确的实体类型"); + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); + return this; + } - public virtual string ToSql() { - if (_source == null || _source.Any() == false) return null; - var sb = new StringBuilder(); - sb.Append("INSERT INTO ").Append(_commonUtils.QuoteSqlName(_tableRule?.Invoke(_table.DbName) ?? _table.DbName)).Append("("); - var colidx = 0; - foreach (var col in _table.Columns.Values) - if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)); - ++colidx; - } - sb.Append(") VALUES"); - _params = _noneParameter ? new DbParameter[0] : new DbParameter[colidx * _source.Count]; - var specialParams = new List(); - var didx = 0; - foreach (var d in _source) { - if (didx > 0) sb.Append(", "); - sb.Append("("); - var colidx2 = 0; - foreach (var col in _table.Columns.Values) - if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) { - if (colidx2 > 0) sb.Append(", "); - object val = col.GetMapValue(d); - if (col.Attribute.IsPrimary && col.Attribute.MapType.NullableTypeOrThis() == typeof(Guid) && (val == null || (Guid)val == Guid.Empty)) - col.SetMapValue(d, val = FreeUtil.NewMongodbId()); - if (_noneParameter) - sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); - else { - sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); - _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col.Attribute.MapType, val); - } - ++colidx2; - } - sb.Append(")"); - ++didx; - } - if (_noneParameter && specialParams.Any()) - _params = specialParams.ToArray(); - return sb.ToString(); - } - } + public virtual string ToSql() + { + if (_source == null || _source.Any() == false) return null; + var sb = new StringBuilder(); + sb.Append("INSERT INTO ").Append(_commonUtils.QuoteSqlName(_tableRule?.Invoke(_table.DbName) ?? _table.DbName)).Append("("); + var colidx = 0; + foreach (var col in _table.Columns.Values) + if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)); + ++colidx; + } + sb.Append(") VALUES"); + _params = _noneParameter ? new DbParameter[0] : new DbParameter[colidx * _source.Count]; + var specialParams = new List(); + var didx = 0; + foreach (var d in _source) + { + if (didx > 0) sb.Append(", "); + sb.Append("("); + var colidx2 = 0; + foreach (var col in _table.Columns.Values) + if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) + { + if (colidx2 > 0) sb.Append(", "); + object val = col.GetMapValue(d); + if (col.Attribute.IsPrimary && col.Attribute.MapType.NullableTypeOrThis() == typeof(Guid) && (val == null || (Guid)val == Guid.Empty)) + col.SetMapValue(d, val = FreeUtil.NewMongodbId()); + if (_noneParameter) + sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); + else + { + sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); + _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col.Attribute.MapType, val); + } + ++colidx2; + } + sb.Append(")"); + ++didx; + } + if (_noneParameter && specialParams.Any()) + _params = specialParams.ToArray(); + return sb.ToString(); + } + } } diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select0Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select0Provider.cs index bb43b573..32b794e6 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select0Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select0Provider.cs @@ -12,889 +12,1035 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select0Provider : ISelect0 where TSelect : class where T1 : class { + public abstract class Select0Provider : ISelect0 where TSelect : class where T1 : class + { - protected int _limit, _skip; - protected string _select = "SELECT ", _orderby, _groupby, _having; - protected StringBuilder _where = new StringBuilder(); - protected List _params = new List(); - protected List _tables = new List(); - protected List> _tableRules = new List>(); - protected StringBuilder _join = new StringBuilder(); - protected IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - protected DbTransaction _transaction; - protected DbConnection _connection; - protected Action _trackToList; - protected Queue> _includeToList = new Queue>(); - protected bool _distinct; - protected Expression _selectExpression; + protected int _limit, _skip; + protected string _select = "SELECT ", _orderby, _groupby, _having; + protected StringBuilder _where = new StringBuilder(); + protected List _params = new List(); + protected List _tables = new List(); + protected List> _tableRules = new List>(); + protected StringBuilder _join = new StringBuilder(); + protected IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + protected DbTransaction _transaction; + protected DbConnection _connection; + protected Action _trackToList; + protected Queue> _includeToList = new Queue>(); + protected bool _distinct; + protected Expression _selectExpression; - public static void CopyData(Select0Provider from, object to, ReadOnlyCollection lambParms) { - var toType = to?.GetType(); - if (toType == null) return; - toType.GetField("_limit", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._limit); - toType.GetField("_skip", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._skip); - toType.GetField("_select", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._select); - toType.GetField("_orderby", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._orderby); - toType.GetField("_groupby", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._groupby); - toType.GetField("_having", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._having); - toType.GetField("_where", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, new StringBuilder().Append(from._where.ToString())); - toType.GetField("_params", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, new List(from._params.ToArray())); - if (lambParms == null) - toType.GetField("_tables", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, new List(from._tables.ToArray())); - else { - var _multiTables = toType.GetField("_tables", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(to) as List; - _multiTables[0] = from._tables[0]; - for (var a = 1; a < lambParms.Count; a++) { - var tb = from._tables.Where(b => b.Alias == lambParms[a].Name && b.Table.Type == lambParms[a].Type).FirstOrDefault(); - if (tb != null) _multiTables[a] = tb; - else { - _multiTables[a].Alias = lambParms[a].Name; - _multiTables[a].Parameter = lambParms[a]; - } - } - if (_multiTables.Count < from._tables.Count) - _multiTables.AddRange(from._tables.GetRange(_multiTables.Count, from._tables.Count - _multiTables.Count)); - } - toType.GetField("_tableRules", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._tableRules); - toType.GetField("_join", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, new StringBuilder().Append(from._join.ToString())); - //toType.GetField("_orm", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._orm); - //toType.GetField("_commonUtils", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._commonUtils); - //toType.GetField("_commonExpression", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._commonExpression); - toType.GetField("_transaction", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._transaction); - toType.GetField("_connection", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._connection); - toType.GetField("_trackToList", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._trackToList); - toType.GetField("_includeToList", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._includeToList); - toType.GetField("_distinct", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._distinct); - toType.GetField("_selectExpression", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._selectExpression); - } + public static void CopyData(Select0Provider from, object to, ReadOnlyCollection lambParms) + { + var toType = to?.GetType(); + if (toType == null) return; + toType.GetField("_limit", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._limit); + toType.GetField("_skip", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._skip); + toType.GetField("_select", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._select); + toType.GetField("_orderby", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._orderby); + toType.GetField("_groupby", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._groupby); + toType.GetField("_having", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._having); + toType.GetField("_where", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, new StringBuilder().Append(from._where.ToString())); + toType.GetField("_params", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, new List(from._params.ToArray())); + if (lambParms == null) + toType.GetField("_tables", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, new List(from._tables.ToArray())); + else + { + var _multiTables = toType.GetField("_tables", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(to) as List; + _multiTables[0] = from._tables[0]; + for (var a = 1; a < lambParms.Count; a++) + { + var tb = from._tables.Where(b => b.Alias == lambParms[a].Name && b.Table.Type == lambParms[a].Type).FirstOrDefault(); + if (tb != null) _multiTables[a] = tb; + else + { + _multiTables[a].Alias = lambParms[a].Name; + _multiTables[a].Parameter = lambParms[a]; + } + } + if (_multiTables.Count < from._tables.Count) + _multiTables.AddRange(from._tables.GetRange(_multiTables.Count, from._tables.Count - _multiTables.Count)); + } + toType.GetField("_tableRules", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._tableRules); + toType.GetField("_join", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, new StringBuilder().Append(from._join.ToString())); + //toType.GetField("_orm", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._orm); + //toType.GetField("_commonUtils", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._commonUtils); + //toType.GetField("_commonExpression", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._commonExpression); + toType.GetField("_transaction", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._transaction); + toType.GetField("_connection", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._connection); + toType.GetField("_trackToList", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._trackToList); + toType.GetField("_includeToList", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._includeToList); + toType.GetField("_distinct", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._distinct); + toType.GetField("_selectExpression", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(to, from._selectExpression); + } - public Select0Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T1)), Alias = "a", On = null, Type = SelectTableInfoType.From }); - this.Where(_commonUtils.WhereObject(_tables.First().Table, "a.", dywhere)); - if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); - } + public Select0Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T1)), Alias = "a", On = null, Type = SelectTableInfoType.From }); + this.Where(_commonUtils.WhereObject(_tables.First().Table, "a.", dywhere)); + if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); + } - public TSelect TrackToList(Action track) { - _trackToList = track; - return this as TSelect; - } + public TSelect TrackToList(Action track) + { + _trackToList = track; + return this as TSelect; + } - public TSelect WithTransaction(DbTransaction transaction) { - _transaction = transaction; - _connection = _transaction?.Connection; - return this as TSelect; - } - public TSelect WithConnection(DbConnection connection) { - if (_transaction?.Connection != connection) _transaction = null; - _connection = connection; - return this as TSelect; - } + public TSelect WithTransaction(DbTransaction transaction) + { + _transaction = transaction; + _connection = _transaction?.Connection; + return this as TSelect; + } + public TSelect WithConnection(DbConnection connection) + { + if (_transaction?.Connection != connection) _transaction = null; + _connection = connection; + return this as TSelect; + } - public bool Any() { - this.Limit(1); - return this.ToList("1").FirstOrDefault() == 1; - } - async public Task AnyAsync() { - this.Limit(1); - return (await this.ToListAsync("1")).FirstOrDefault() == 1; - } + public bool Any() + { + this.Limit(1); + return this.ToList("1").FirstOrDefault() == 1; + } + async public Task AnyAsync() + { + this.Limit(1); + return (await this.ToListAsync("1")).FirstOrDefault() == 1; + } - public long Count() => this.ToList("count(1)").FirstOrDefault(); - async public Task CountAsync() => (await this.ToListAsync("count(1)")).FirstOrDefault(); + public long Count() => this.ToList("count(1)").FirstOrDefault(); + async public Task CountAsync() => (await this.ToListAsync("count(1)")).FirstOrDefault(); - public TSelect Count(out long count) { - count = this.Count(); - return this as TSelect; - } + public TSelect Count(out long count) + { + count = this.Count(); + return this as TSelect; + } - public TSelect GroupBy(string sql, object parms = null) { - _groupby = sql; - if (string.IsNullOrEmpty(_groupby)) return this as TSelect; - _groupby = string.Concat(" \r\nGROUP BY ", _groupby); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(_groupby, parms)); - return this as TSelect; - } - public TSelect Having(string sql, object parms = null) { - if (string.IsNullOrEmpty(_groupby) || string.IsNullOrEmpty(sql)) return this as TSelect; - _having = string.Concat(_having, " AND (", sql, ")"); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this as TSelect; - } + public TSelect GroupBy(string sql, object parms = null) + { + _groupby = sql; + if (string.IsNullOrEmpty(_groupby)) return this as TSelect; + _groupby = string.Concat(" \r\nGROUP BY ", _groupby); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(_groupby, parms)); + return this as TSelect; + } + public TSelect Having(string sql, object parms = null) + { + if (string.IsNullOrEmpty(_groupby) || string.IsNullOrEmpty(sql)) return this as TSelect; + _having = string.Concat(_having, " AND (", sql, ")"); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this as TSelect; + } - public TSelect LeftJoin(Expression> exp) { - if (exp == null) return this as TSelect; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalJoin(exp?.Body, SelectTableInfoType.LeftJoin); - } - public TSelect InnerJoin(Expression> exp) { - if (exp == null) return this as TSelect; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalJoin(exp?.Body, SelectTableInfoType.InnerJoin); - } - public TSelect RightJoin(Expression> exp) { - if (exp == null) return this as TSelect; _tables[0].Parameter = exp.Parameters[0]; - return this.InternalJoin(exp?.Body, SelectTableInfoType.RightJoin); - } - public TSelect LeftJoin(Expression> exp) { - if (exp == null) return this as TSelect; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalJoin(exp?.Body, SelectTableInfoType.LeftJoin); - } - public TSelect InnerJoin(Expression> exp) { - if (exp == null) return this as TSelect; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalJoin(exp?.Body, SelectTableInfoType.InnerJoin); - } - public TSelect RightJoin(Expression> exp) { - if (exp == null) return this as TSelect; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalJoin(exp?.Body, SelectTableInfoType.RightJoin); - } + public TSelect LeftJoin(Expression> exp) + { + if (exp == null) return this as TSelect; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalJoin(exp?.Body, SelectTableInfoType.LeftJoin); + } + public TSelect InnerJoin(Expression> exp) + { + if (exp == null) return this as TSelect; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalJoin(exp?.Body, SelectTableInfoType.InnerJoin); + } + public TSelect RightJoin(Expression> exp) + { + if (exp == null) return this as TSelect; _tables[0].Parameter = exp.Parameters[0]; + return this.InternalJoin(exp?.Body, SelectTableInfoType.RightJoin); + } + public TSelect LeftJoin(Expression> exp) + { + if (exp == null) return this as TSelect; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalJoin(exp?.Body, SelectTableInfoType.LeftJoin); + } + public TSelect InnerJoin(Expression> exp) + { + if (exp == null) return this as TSelect; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalJoin(exp?.Body, SelectTableInfoType.InnerJoin); + } + public TSelect RightJoin(Expression> exp) + { + if (exp == null) return this as TSelect; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalJoin(exp?.Body, SelectTableInfoType.RightJoin); + } - public TSelect InnerJoin(string sql, object parms = null) { - if (string.IsNullOrEmpty(sql)) return this as TSelect; - _join.Append(" \r\nINNER JOIN ").Append(sql); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this as TSelect; - } - public TSelect LeftJoin(string sql, object parms = null) { - if (string.IsNullOrEmpty(sql)) return this as TSelect; - _join.Append(" \r\nLEFT JOIN ").Append(sql); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this as TSelect; - } + public TSelect InnerJoin(string sql, object parms = null) + { + if (string.IsNullOrEmpty(sql)) return this as TSelect; + _join.Append(" \r\nINNER JOIN ").Append(sql); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this as TSelect; + } + public TSelect LeftJoin(string sql, object parms = null) + { + if (string.IsNullOrEmpty(sql)) return this as TSelect; + _join.Append(" \r\nLEFT JOIN ").Append(sql); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this as TSelect; + } - public TSelect Limit(int limit) { - _limit = limit; - return this as TSelect; - } - public TSelect Master() { - _select = " SELECT "; - return this as TSelect; - } - public TSelect Offset(int offset) => this.Skip(offset) as TSelect; + public TSelect Limit(int limit) + { + _limit = limit; + return this as TSelect; + } + public TSelect Master() + { + _select = " SELECT "; + return this as TSelect; + } + public TSelect Offset(int offset) => this.Skip(offset) as TSelect; - public TSelect OrderBy(string sql, object parms = null) => this.OrderBy(true, sql, parms); - public TSelect OrderBy(bool condition, string sql, object parms = null) { - if (condition == false) return this as TSelect; - if (string.IsNullOrEmpty(sql)) _orderby = null; - var isnull = string.IsNullOrEmpty(_orderby); - _orderby = string.Concat(isnull ? " \r\nORDER BY " : "", _orderby, isnull ? "" : ", ", sql); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this as TSelect; - } - public TSelect Page(int pageNumber, int pageSize) { - this.Skip(Math.Max(0, pageNumber - 1) * pageSize); - return this.Limit(pageSize) as TSelect; - } + public TSelect OrderBy(string sql, object parms = null) => this.OrderBy(true, sql, parms); + public TSelect OrderBy(bool condition, string sql, object parms = null) + { + if (condition == false) return this as TSelect; + if (string.IsNullOrEmpty(sql)) _orderby = null; + var isnull = string.IsNullOrEmpty(_orderby); + _orderby = string.Concat(isnull ? " \r\nORDER BY " : "", _orderby, isnull ? "" : ", ", sql); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this as TSelect; + } + public TSelect Page(int pageNumber, int pageSize) + { + this.Skip(Math.Max(0, pageNumber - 1) * pageSize); + return this.Limit(pageSize) as TSelect; + } - public TSelect RightJoin(string sql, object parms = null) { - if (string.IsNullOrEmpty(sql)) return this as TSelect; - _join.Append(" \r\nRIGHT JOIN ").Append(sql); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this as TSelect; - } + public TSelect RightJoin(string sql, object parms = null) + { + if (string.IsNullOrEmpty(sql)) return this as TSelect; + _join.Append(" \r\nRIGHT JOIN ").Append(sql); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this as TSelect; + } - public TSelect Skip(int offset) { - _skip = offset; - return this as TSelect; - } - public TSelect Take(int limit) => this.Limit(limit) as TSelect; + public TSelect Skip(int offset) + { + _skip = offset; + return this as TSelect; + } + public TSelect Take(int limit) => this.Limit(limit) as TSelect; - public TSelect Distinct() { - _distinct = true; - return this as TSelect; - } + public TSelect Distinct() + { + _distinct = true; + return this as TSelect; + } - public DataTable ToDataTable(string field = null) { - var sql = this.ToSql(field); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - DataTable ret = null; - Exception exception = null; - try { - ret = _orm.Ado.ExecuteDataTable(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - return ret; - } - async public Task ToDataTableAsync(string field = null) { - var sql = this.ToSql(field); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - DataTable ret = null; - Exception exception = null; - try { - ret = await _orm.Ado.ExecuteDataTableAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - return ret; - } + public DataTable ToDataTable(string field = null) + { + var sql = this.ToSql(field); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + DataTable ret = null; + Exception exception = null; + try + { + ret = _orm.Ado.ExecuteDataTable(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + return ret; + } + async public Task ToDataTableAsync(string field = null) + { + var sql = this.ToSql(field); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + DataTable ret = null; + Exception exception = null; + try + { + ret = await _orm.Ado.ExecuteDataTableAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + return ret; + } - public List ToList(string field) { - var sql = this.ToSql(field); - var type = typeof(TTuple); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - var flagStr = $"ToListField:{field}"; - Exception exception = null; - try { - _orm.Ado.ExecuteReader(_connection, _transaction, dr => { - var read = Utils.ExecuteArrayRowReadClassOrTuple(flagStr, type, null, dr, 0, _commonUtils); - ret.Add((TTuple)read.Value); - }, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - return ret; - } - async public Task> ToListAsync(string field) { - var sql = this.ToSql(field); - var type = typeof(TTuple); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - var flagStr = $"ToListField:{field}"; - Exception exception = null; - try { - await _orm.Ado.ExecuteReaderAsync(_connection, _transaction, dr => { - var read = Utils.ExecuteArrayRowReadClassOrTuple(flagStr, type, null, dr, 0, _commonUtils); - ret.Add((TTuple)read.Value); - return Task.FromResult(false); - }, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - return ret; - } - internal List ToListAfPrivate(string sql, GetAllFieldExpressionTreeInfo af, (string field, ReadAnonymousTypeInfo read, List retlist)[] otherData) { - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - _orm.Ado.ExecuteReader(_connection, _transaction, dr => { - ret.Add(af.Read(_orm, dr)); - if (otherData != null) { - var idx = af.FieldCount - 1; - foreach (var other in otherData) - other.retlist.Add(_commonExpression.ReadAnonymous(other.read, dr, ref idx, false)); - } - }, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - while (_includeToList.Any()) _includeToList.Dequeue()?.Invoke(ret); - _orm.Aop.ToList?.Invoke(this, new Aop.ToListEventArgs(ret)); - _trackToList?.Invoke(ret); - return ret; - } - async internal Task> ToListAfPrivateAsync(string sql, GetAllFieldExpressionTreeInfo af, (string field, ReadAnonymousTypeInfo read, List retlist)[] otherData) { - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - await _orm.Ado.ExecuteReaderAsync(_connection, _transaction, dr => { - ret.Add(af.Read(_orm, dr)); - if (otherData != null) { - var idx = af.FieldCount - 1; - foreach (var other in otherData) - other.retlist.Add(_commonExpression.ReadAnonymous(other.read, dr, ref idx, false)); - } - return Task.FromResult(false); - }, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - while (_includeToList.Any()) _includeToList.Dequeue()?.Invoke(ret); - _orm.Aop.ToList?.Invoke(this, new Aop.ToListEventArgs(ret)); - _trackToList?.Invoke(ret); - return ret; - } - internal List ToListPrivate(GetAllFieldExpressionTreeInfo af, (string field, ReadAnonymousTypeInfo read, List retlist)[] otherData) { - string sql = null; - if (otherData?.Length > 0) { - var sbField = new StringBuilder().Append(af.Field); - foreach (var other in otherData) - sbField.Append(other.field); - sql = this.ToSql(sbField.ToString()); - } else - sql = this.ToSql(af.Field); + public List ToList(string field) + { + var sql = this.ToSql(field); + var type = typeof(TTuple); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + var flagStr = $"ToListField:{field}"; + Exception exception = null; + try + { + _orm.Ado.ExecuteReader(_connection, _transaction, dr => + { + var read = Utils.ExecuteArrayRowReadClassOrTuple(flagStr, type, null, dr, 0, _commonUtils); + ret.Add((TTuple)read.Value); + }, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + return ret; + } + async public Task> ToListAsync(string field) + { + var sql = this.ToSql(field); + var type = typeof(TTuple); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + var flagStr = $"ToListField:{field}"; + Exception exception = null; + try + { + await _orm.Ado.ExecuteReaderAsync(_connection, _transaction, dr => + { + var read = Utils.ExecuteArrayRowReadClassOrTuple(flagStr, type, null, dr, 0, _commonUtils); + ret.Add((TTuple)read.Value); + return Task.FromResult(false); + }, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + return ret; + } + internal List ToListAfPrivate(string sql, GetAllFieldExpressionTreeInfo af, (string field, ReadAnonymousTypeInfo read, List retlist)[] otherData) + { + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + _orm.Ado.ExecuteReader(_connection, _transaction, dr => + { + ret.Add(af.Read(_orm, dr)); + if (otherData != null) + { + var idx = af.FieldCount - 1; + foreach (var other in otherData) + other.retlist.Add(_commonExpression.ReadAnonymous(other.read, dr, ref idx, false)); + } + }, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + while (_includeToList.Any()) _includeToList.Dequeue()?.Invoke(ret); + _orm.Aop.ToList?.Invoke(this, new Aop.ToListEventArgs(ret)); + _trackToList?.Invoke(ret); + return ret; + } + async internal Task> ToListAfPrivateAsync(string sql, GetAllFieldExpressionTreeInfo af, (string field, ReadAnonymousTypeInfo read, List retlist)[] otherData) + { + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + await _orm.Ado.ExecuteReaderAsync(_connection, _transaction, dr => + { + ret.Add(af.Read(_orm, dr)); + if (otherData != null) + { + var idx = af.FieldCount - 1; + foreach (var other in otherData) + other.retlist.Add(_commonExpression.ReadAnonymous(other.read, dr, ref idx, false)); + } + return Task.FromResult(false); + }, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + while (_includeToList.Any()) _includeToList.Dequeue()?.Invoke(ret); + _orm.Aop.ToList?.Invoke(this, new Aop.ToListEventArgs(ret)); + _trackToList?.Invoke(ret); + return ret; + } + internal List ToListPrivate(GetAllFieldExpressionTreeInfo af, (string field, ReadAnonymousTypeInfo read, List retlist)[] otherData) + { + string sql = null; + if (otherData?.Length > 0) + { + var sbField = new StringBuilder().Append(af.Field); + foreach (var other in otherData) + sbField.Append(other.field); + sql = this.ToSql(sbField.ToString()); + } + else + sql = this.ToSql(af.Field); - return ToListAfPrivate(sql, af, otherData); - } - internal Task> ToListPrivateAsync(GetAllFieldExpressionTreeInfo af, (string field, ReadAnonymousTypeInfo read, List retlist)[] otherData) { - string sql = null; - if (otherData?.Length > 0) { - var sbField = new StringBuilder().Append(af.Field); - foreach (var other in otherData) - sbField.Append(other.field); - sql = this.ToSql(sbField.ToString()); - } else - sql = this.ToSql(af.Field); + return ToListAfPrivate(sql, af, otherData); + } + internal Task> ToListPrivateAsync(GetAllFieldExpressionTreeInfo af, (string field, ReadAnonymousTypeInfo read, List retlist)[] otherData) + { + string sql = null; + if (otherData?.Length > 0) + { + var sbField = new StringBuilder().Append(af.Field); + foreach (var other in otherData) + sbField.Append(other.field); + sql = this.ToSql(sbField.ToString()); + } + else + sql = this.ToSql(af.Field); - return ToListAfPrivateAsync(sql, af, otherData); - } - public List ToList(bool includeNestedMembers = false) { - if (_selectExpression != null) return this.InternalToList(_selectExpression); - return this.ToListPrivate(includeNestedMembers == false ? this.GetAllFieldExpressionTreeLevel2() : this.GetAllFieldExpressionTreeLevelAll(), null); - } - public Task> ToListAsync(bool includeNestedMembers = false) { - if (_selectExpression != null) return this.InternalToListAsync(_selectExpression); - return this.ToListPrivateAsync(includeNestedMembers == false ? this.GetAllFieldExpressionTreeLevel2() : this.GetAllFieldExpressionTreeLevelAll(), null); - } - public T1 ToOne() { - this.Limit(1); - return this.ToList().FirstOrDefault(); - } - async public Task ToOneAsync() { - this.Limit(1); - return (await this.ToListAsync()).FirstOrDefault(); - } + return ToListAfPrivateAsync(sql, af, otherData); + } + public List ToList(bool includeNestedMembers = false) + { + if (_selectExpression != null) return this.InternalToList(_selectExpression); + return this.ToListPrivate(includeNestedMembers == false ? this.GetAllFieldExpressionTreeLevel2() : this.GetAllFieldExpressionTreeLevelAll(), null); + } + public Task> ToListAsync(bool includeNestedMembers = false) + { + if (_selectExpression != null) return this.InternalToListAsync(_selectExpression); + return this.ToListPrivateAsync(includeNestedMembers == false ? this.GetAllFieldExpressionTreeLevel2() : this.GetAllFieldExpressionTreeLevelAll(), null); + } + public T1 ToOne() + { + this.Limit(1); + return this.ToList().FirstOrDefault(); + } + async public Task ToOneAsync() + { + this.Limit(1); + return (await this.ToListAsync()).FirstOrDefault(); + } - public T1 First() => this.ToOne(); - public Task FirstAsync() => this.ToOneAsync(); + public T1 First() => this.ToOne(); + public Task FirstAsync() => this.ToOneAsync(); - protected List ToListMapReader((ReadAnonymousTypeInfo map, string field) af) { - var sql = this.ToSql(af.field); - var type = typeof(TReturn); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - _orm.Ado.ExecuteReader(_connection, _transaction, dr => { - var index = -1; - ret.Add((TReturn)_commonExpression.ReadAnonymous(af.map, dr, ref index, false)); - }, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - _orm.Aop.ToList?.Invoke(this, new Aop.ToListEventArgs(ret)); - _trackToList?.Invoke(ret); - return ret; - } - async protected Task> ToListMapReaderAsync((ReadAnonymousTypeInfo map, string field) af) { - var sql = this.ToSql(af.field); - var type = typeof(TReturn); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - await _orm.Ado.ExecuteReaderAsync(_connection, _transaction, dr => { - var index = -1; - ret.Add((TReturn)_commonExpression.ReadAnonymous(af.map, dr, ref index, false)); - return Task.FromResult(false); - }, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - _orm.Aop.ToList?.Invoke(this, new Aop.ToListEventArgs(ret)); - _trackToList?.Invoke(ret); - return ret; - } - protected (ReadAnonymousTypeInfo map, string field) GetExpressionField(Expression newexp) { - var map = new ReadAnonymousTypeInfo(); - var field = new StringBuilder(); - var index = 0; + protected List ToListMapReader((ReadAnonymousTypeInfo map, string field) af) + { + var sql = this.ToSql(af.field); + var type = typeof(TReturn); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + _orm.Ado.ExecuteReader(_connection, _transaction, dr => + { + var index = -1; + ret.Add((TReturn)_commonExpression.ReadAnonymous(af.map, dr, ref index, false)); + }, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + _orm.Aop.ToList?.Invoke(this, new Aop.ToListEventArgs(ret)); + _trackToList?.Invoke(ret); + return ret; + } + async protected Task> ToListMapReaderAsync((ReadAnonymousTypeInfo map, string field) af) + { + var sql = this.ToSql(af.field); + var type = typeof(TReturn); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + await _orm.Ado.ExecuteReaderAsync(_connection, _transaction, dr => + { + var index = -1; + ret.Add((TReturn)_commonExpression.ReadAnonymous(af.map, dr, ref index, false)); + return Task.FromResult(false); + }, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + _orm.Aop.ToList?.Invoke(this, new Aop.ToListEventArgs(ret)); + _trackToList?.Invoke(ret); + return ret; + } + protected (ReadAnonymousTypeInfo map, string field) GetExpressionField(Expression newexp) + { + var map = new ReadAnonymousTypeInfo(); + var field = new StringBuilder(); + var index = 0; - _commonExpression.ReadAnonymousField(_tables, field, map, ref index, newexp, null); - return (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null); - } - static ConcurrentDictionary _dicConstructor = new ConcurrentDictionary(); - static ConcurrentDictionary _dicGetAllFieldExpressionTree = new ConcurrentDictionary(); - public class GetAllFieldExpressionTreeInfo { - public string Field { get; set; } - public int FieldCount { get; set; } - public Func Read { get; set; } - } - protected GetAllFieldExpressionTreeInfo GetAllFieldExpressionTreeLevelAll() { - return _dicGetAllFieldExpressionTree.GetOrAdd($"*{string.Join("+", _tables.Select(a => $"{_orm.Ado.DataType}-{a.Table.DbName}-{a.Alias}-{a.Type}"))}", s => { - var type = _tables.First().Table.TypeLazy ?? _tables.First().Table.Type; - var ormExp = Expression.Parameter(typeof(IFreeSql), "orm"); - var rowExp = Expression.Parameter(typeof(DbDataReader), "row"); - var returnTarget = Expression.Label(type); - var retExp = Expression.Variable(type, "ret"); - var dataIndexExp = Expression.Variable(typeof(int), "dataIndex"); - var readExp = Expression.Variable(typeof(Utils.RowInfo), "read"); - var readExpValue = Expression.MakeMemberAccess(readExp, Utils.RowInfo.PropertyValue); - var readExpDataIndex = Expression.MakeMemberAccess(readExp, Utils.RowInfo.PropertyDataIndex); - var blockExp = new List(); - var ctor = type.GetConstructor(new Type[0]) ?? type.GetConstructors().First(); - blockExp.AddRange(new Expression[] { - Expression.Assign(retExp, Expression.New(ctor, ctor.GetParameters().Select(a => Expression.Default(a.ParameterType)))), - Expression.Assign(dataIndexExp, Expression.Constant(0)) - }); - //typeof(Topic).GetMethod("get_Type").IsVirtual + _commonExpression.ReadAnonymousField(_tables, field, map, ref index, newexp, null); + return (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null); + } + static ConcurrentDictionary _dicConstructor = new ConcurrentDictionary(); + static ConcurrentDictionary _dicGetAllFieldExpressionTree = new ConcurrentDictionary(); + public class GetAllFieldExpressionTreeInfo + { + public string Field { get; set; } + public int FieldCount { get; set; } + public Func Read { get; set; } + } + protected GetAllFieldExpressionTreeInfo GetAllFieldExpressionTreeLevelAll() + { + return _dicGetAllFieldExpressionTree.GetOrAdd($"*{string.Join("+", _tables.Select(a => $"{_orm.Ado.DataType}-{a.Table.DbName}-{a.Alias}-{a.Type}"))}", s => + { + var type = _tables.First().Table.TypeLazy ?? _tables.First().Table.Type; + var ormExp = Expression.Parameter(typeof(IFreeSql), "orm"); + var rowExp = Expression.Parameter(typeof(DbDataReader), "row"); + var returnTarget = Expression.Label(type); + var retExp = Expression.Variable(type, "ret"); + var dataIndexExp = Expression.Variable(typeof(int), "dataIndex"); + var readExp = Expression.Variable(typeof(Utils.RowInfo), "read"); + var readExpValue = Expression.MakeMemberAccess(readExp, Utils.RowInfo.PropertyValue); + var readExpDataIndex = Expression.MakeMemberAccess(readExp, Utils.RowInfo.PropertyDataIndex); + var blockExp = new List(); + var ctor = type.GetConstructor(new Type[0]) ?? type.GetConstructors().First(); + blockExp.AddRange(new Expression[] { + Expression.Assign(retExp, Expression.New(ctor, ctor.GetParameters().Select(a => Expression.Default(a.ParameterType)))), + Expression.Assign(dataIndexExp, Expression.Constant(0)) + }); + //typeof(Topic).GetMethod("get_Type").IsVirtual - var field = new StringBuilder(); - var dicfield = new Dictionary(); - var tb = _tables.First(); - var index = 0; + var field = new StringBuilder(); + var dicfield = new Dictionary(); + var tb = _tables.First(); + var index = 0; - var tborder = new[] { tb }.Concat(_tables.ToArray().Where((a, b) => b > 0).OrderBy(a => a.Alias)); - var tbiindex = 0; - foreach (var tbi in tborder) { - if (tbiindex > 0 && tbi.Type == SelectTableInfoType.From) continue; - if (tbiindex > 0 && tbi.Alias.StartsWith($"{tb.Alias}__") == false) continue; + var tborder = new[] { tb }.Concat(_tables.ToArray().Where((a, b) => b > 0).OrderBy(a => a.Alias)); + var tbiindex = 0; + foreach (var tbi in tborder) + { + if (tbiindex > 0 && tbi.Type == SelectTableInfoType.From) continue; + if (tbiindex > 0 && tbi.Alias.StartsWith($"{tb.Alias}__") == false) continue; - var typei = tbi.Table.TypeLazy ?? tbi.Table.Type; - Expression curExp = retExp; + var typei = tbi.Table.TypeLazy ?? tbi.Table.Type; + Expression curExp = retExp; - var colidx = 0; - foreach (var col in tbi.Table.Columns.Values) { - if (index > 0) { - field.Append(", "); - if (tbiindex > 0 && colidx == 0) field.Append("\r\n"); - } - var quoteName = _commonUtils.QuoteSqlName(col.Attribute.Name); - field.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"{tbi.Alias}.{quoteName}")); - ++index; - if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); - else dicfield.Add(quoteName, true); - ++colidx; - } - tbiindex++; + var colidx = 0; + foreach (var col in tbi.Table.Columns.Values) + { + if (index > 0) + { + field.Append(", "); + if (tbiindex > 0 && colidx == 0) field.Append("\r\n"); + } + var quoteName = _commonUtils.QuoteSqlName(col.Attribute.Name); + field.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"{tbi.Alias}.{quoteName}")); + ++index; + if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); + else dicfield.Add(quoteName, true); + ++colidx; + } + tbiindex++; - if (tbiindex == 0) - blockExp.AddRange(new Expression[] { - Expression.Assign(readExp, Expression.Call(Utils.MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(null, typeof(string)), Expression.Constant(typei), Expression.Constant(null, typeof(int[])), rowExp, dataIndexExp, Expression.Constant(_commonUtils) })), - Expression.IfThen( - Expression.GreaterThan(readExpDataIndex, dataIndexExp), - Expression.Assign(dataIndexExp, readExpDataIndex) - ), - Expression.IfThen( - Expression.NotEqual(readExpValue, Expression.Constant(null)), - Expression.Assign(retExp, Expression.Convert(readExpValue, typei)) - ) - }); - else { - Expression curExpIfNotNull = Expression.IsTrue(Expression.Constant(true)); - var curTb = tb; - var parentNameSplits = tbi.Alias.Split(new[] { "__" }, StringSplitOptions.None); - var iscontinue = false; - for (var k = 1; k < parentNameSplits.Length; k++) { - var curPropName = parentNameSplits[k]; - if (curTb.Table.Properties.TryGetValue(parentNameSplits[k], out var tryprop) == false) { - k++; - curPropName = $"{curPropName}__{parentNameSplits[k]}"; - if (curTb.Table.Properties.TryGetValue(parentNameSplits[k], out tryprop) == false) { - iscontinue = true; - break; - } - } - curExp = Expression.MakeMemberAccess(curExp, tryprop); - if (k + 1 < parentNameSplits.Length) - curExpIfNotNull = Expression.AndAlso(curExpIfNotNull, Expression.NotEqual(curExp, Expression.Default(tryprop.PropertyType))); - curTb = _tables.Where(a => a.Alias == $"{curTb.Alias}__{curPropName}" && a.Table.Type == tryprop.PropertyType).FirstOrDefault(); - if (curTb == null) { - iscontinue = true; - break; - } - } - if (iscontinue) continue; + if (tbiindex == 0) + blockExp.AddRange(new Expression[] { + Expression.Assign(readExp, Expression.Call(Utils.MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(null, typeof(string)), Expression.Constant(typei), Expression.Constant(null, typeof(int[])), rowExp, dataIndexExp, Expression.Constant(_commonUtils) })), + Expression.IfThen( + Expression.GreaterThan(readExpDataIndex, dataIndexExp), + Expression.Assign(dataIndexExp, readExpDataIndex) + ), + Expression.IfThen( + Expression.NotEqual(readExpValue, Expression.Constant(null)), + Expression.Assign(retExp, Expression.Convert(readExpValue, typei)) + ) + }); + else + { + Expression curExpIfNotNull = Expression.IsTrue(Expression.Constant(true)); + var curTb = tb; + var parentNameSplits = tbi.Alias.Split(new[] { "__" }, StringSplitOptions.None); + var iscontinue = false; + for (var k = 1; k < parentNameSplits.Length; k++) + { + var curPropName = parentNameSplits[k]; + if (curTb.Table.Properties.TryGetValue(parentNameSplits[k], out var tryprop) == false) + { + k++; + curPropName = $"{curPropName}__{parentNameSplits[k]}"; + if (curTb.Table.Properties.TryGetValue(parentNameSplits[k], out tryprop) == false) + { + iscontinue = true; + break; + } + } + curExp = Expression.MakeMemberAccess(curExp, tryprop); + if (k + 1 < parentNameSplits.Length) + curExpIfNotNull = Expression.AndAlso(curExpIfNotNull, Expression.NotEqual(curExp, Expression.Default(tryprop.PropertyType))); + curTb = _tables.Where(a => a.Alias == $"{curTb.Alias}__{curPropName}" && a.Table.Type == tryprop.PropertyType).FirstOrDefault(); + if (curTb == null) + { + iscontinue = true; + break; + } + } + if (iscontinue) continue; - blockExp.Add( - Expression.IfThenElse( - curExpIfNotNull, - Expression.Block(new Expression[] { - Expression.Assign(readExp, Expression.Call(Utils.MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(null, typeof(string)), Expression.Constant(typei), Expression.Constant(null, typeof(int[])), rowExp, dataIndexExp, Expression.Constant(_commonUtils) })), - Expression.IfThen( - Expression.GreaterThan(readExpDataIndex, dataIndexExp), - Expression.Assign(dataIndexExp, readExpDataIndex) - ), - Expression.IfThenElse( - Expression.NotEqual(readExpValue, Expression.Constant(null)), - Expression.Assign(curExp, Expression.Convert(readExpValue, typei)), - Expression.Assign(curExp, Expression.Constant(null, typei)) - ) - }), - Expression.Block( - Expression.Assign(readExpValue, Expression.Constant(null, typeof(object))), - Expression.Assign(dataIndexExp, Expression.Constant(index)) - ) - ) - ); - } + blockExp.Add( + Expression.IfThenElse( + curExpIfNotNull, + Expression.Block(new Expression[] { + Expression.Assign(readExp, Expression.Call(Utils.MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(null, typeof(string)), Expression.Constant(typei), Expression.Constant(null, typeof(int[])), rowExp, dataIndexExp, Expression.Constant(_commonUtils) })), + Expression.IfThen( + Expression.GreaterThan(readExpDataIndex, dataIndexExp), + Expression.Assign(dataIndexExp, readExpDataIndex) + ), + Expression.IfThenElse( + Expression.NotEqual(readExpValue, Expression.Constant(null)), + Expression.Assign(curExp, Expression.Convert(readExpValue, typei)), + Expression.Assign(curExp, Expression.Constant(null, typei)) + ) + }), + Expression.Block( + Expression.Assign(readExpValue, Expression.Constant(null, typeof(object))), + Expression.Assign(dataIndexExp, Expression.Constant(index)) + ) + ) + ); + } - if (tbi.Table.TypeLazy != null) - blockExp.Add( - Expression.IfThen( - Expression.NotEqual(readExpValue, Expression.Constant(null)), - Expression.Call(Expression.TypeAs(readExpValue, typei), tbi.Table.TypeLazySetOrm, ormExp) - ) - ); //将 orm 传递给 lazy - } + if (tbi.Table.TypeLazy != null) + blockExp.Add( + Expression.IfThen( + Expression.NotEqual(readExpValue, Expression.Constant(null)), + Expression.Call(Expression.TypeAs(readExpValue, typei), tbi.Table.TypeLazySetOrm, ormExp) + ) + ); //将 orm 传递给 lazy + } - blockExp.AddRange(new Expression[] { - Expression.Return(returnTarget, retExp), - Expression.Label(returnTarget, Expression.Default(type)) - }); - return new GetAllFieldExpressionTreeInfo { - Field = field.ToString(), - FieldCount = index, - Read = Expression.Lambda>(Expression.Block(new[] { retExp, dataIndexExp, readExp }, blockExp), new[] { ormExp, rowExp }).Compile() - }; - }); - } - protected GetAllFieldExpressionTreeInfo GetAllFieldExpressionTreeLevel2() { - return _dicGetAllFieldExpressionTree.GetOrAdd(string.Join("+", _tables.Select(a => $"{_orm.Ado.DataType}-{a.Table.DbName}-{a.Alias}-{a.Type}")), s => { - var tb1 = _tables.First().Table; - var type = tb1.TypeLazy ?? tb1.Type; - var props = tb1.Properties; + blockExp.AddRange(new Expression[] { + Expression.Return(returnTarget, retExp), + Expression.Label(returnTarget, Expression.Default(type)) + }); + return new GetAllFieldExpressionTreeInfo + { + Field = field.ToString(), + FieldCount = index, + Read = Expression.Lambda>(Expression.Block(new[] { retExp, dataIndexExp, readExp }, blockExp), new[] { ormExp, rowExp }).Compile() + }; + }); + } + protected GetAllFieldExpressionTreeInfo GetAllFieldExpressionTreeLevel2() + { + return _dicGetAllFieldExpressionTree.GetOrAdd(string.Join("+", _tables.Select(a => $"{_orm.Ado.DataType}-{a.Table.DbName}-{a.Alias}-{a.Type}")), s => + { + var tb1 = _tables.First().Table; + var type = tb1.TypeLazy ?? tb1.Type; + var props = tb1.Properties; - var ormExp = Expression.Parameter(typeof(IFreeSql), "orm"); - var rowExp = Expression.Parameter(typeof(DbDataReader), "row"); - var returnTarget = Expression.Label(type); - var retExp = Expression.Variable(type, "ret"); - var dataIndexExp = Expression.Variable(typeof(int), "dataIndex"); - var readExp = Expression.Variable(typeof(Utils.RowInfo), "read"); - var readExpValue = Expression.MakeMemberAccess(readExp, Utils.RowInfo.PropertyValue); - var readExpDataIndex = Expression.MakeMemberAccess(readExp, Utils.RowInfo.PropertyDataIndex); - var blockExp = new List(); - var ctor = type.GetConstructor(new Type[0]) ?? type.GetConstructors().First(); - blockExp.AddRange(new Expression[] { - Expression.Assign(retExp, Expression.New(ctor, ctor.GetParameters().Select(a => Expression.Default(a.ParameterType)))), - Expression.Assign(dataIndexExp, Expression.Constant(0)) - }); - //typeof(Topic).GetMethod("get_Type").IsVirtual + var ormExp = Expression.Parameter(typeof(IFreeSql), "orm"); + var rowExp = Expression.Parameter(typeof(DbDataReader), "row"); + var returnTarget = Expression.Label(type); + var retExp = Expression.Variable(type, "ret"); + var dataIndexExp = Expression.Variable(typeof(int), "dataIndex"); + var readExp = Expression.Variable(typeof(Utils.RowInfo), "read"); + var readExpValue = Expression.MakeMemberAccess(readExp, Utils.RowInfo.PropertyValue); + var readExpDataIndex = Expression.MakeMemberAccess(readExp, Utils.RowInfo.PropertyDataIndex); + var blockExp = new List(); + var ctor = type.GetConstructor(new Type[0]) ?? type.GetConstructors().First(); + blockExp.AddRange(new Expression[] { + Expression.Assign(retExp, Expression.New(ctor, ctor.GetParameters().Select(a => Expression.Default(a.ParameterType)))), + Expression.Assign(dataIndexExp, Expression.Constant(0)) + }); + //typeof(Topic).GetMethod("get_Type").IsVirtual - var field = new StringBuilder(); - var dicfield = new Dictionary(); - var tb = _tables.First(); - var index = 0; - var otherindex = 0; - foreach (var prop in props.Values) { - if (tb.Table.ColumnsByCsIgnore.ContainsKey(prop.Name)) continue; + var field = new StringBuilder(); + var dicfield = new Dictionary(); + var tb = _tables.First(); + var index = 0; + var otherindex = 0; + foreach (var prop in props.Values) + { + if (tb.Table.ColumnsByCsIgnore.ContainsKey(prop.Name)) continue; - if (tb.Table.ColumnsByCs.TryGetValue(prop.Name, out var col)) { //普通字段 - if (index > 0) field.Append(", "); - var quoteName = _commonUtils.QuoteSqlName(col.Attribute.Name); - field.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"{tb.Alias}.{quoteName}")); - ++index; - if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); - else dicfield.Add(quoteName, true); - } else { - var tb2 = _tables.Where((a, b) => b > 0 && - (a.Type == SelectTableInfoType.InnerJoin || a.Type == SelectTableInfoType.LeftJoin || a.Type == SelectTableInfoType.RightJoin) && - string.IsNullOrEmpty(a.On) == false && - a.Alias.StartsWith($"{tb.Alias}__") && //开头结尾完全匹配 - a.Alias.EndsWith($"__{prop.Name}") //不清楚会不会有其他情况 求大佬优化 - ).FirstOrDefault(); //判断 b > 0 防止 parent 递归关系 - if (tb2 == null && props.Where(pw => pw.Value.PropertyType == prop.PropertyType).Count() == 1) - tb2 = _tables.Where((a, b) => b > 0 && - (a.Type == SelectTableInfoType.InnerJoin || a.Type == SelectTableInfoType.LeftJoin || a.Type == SelectTableInfoType.RightJoin) && - string.IsNullOrEmpty(a.On) == false && - a.Table.Type == prop.PropertyType).FirstOrDefault(); - if (tb2 == null) continue; - foreach (var col2 in tb2.Table.Columns.Values) { - if (index > 0) field.Append(", "); - var quoteName = _commonUtils.QuoteSqlName(col2.Attribute.Name); - field.Append(_commonUtils.QuoteReadColumn(col2.Attribute.MapType, $"{tb2.Alias}.{quoteName}")); - ++index; - ++otherindex; - if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); - else dicfield.Add(quoteName, true); - } - } - //只读到二级属性 - var propGetSetMethod = prop.GetSetMethod(); - Expression readExpAssign = null; //加速缓存 - if (prop.PropertyType.IsArray) readExpAssign = Expression.New(Utils.RowInfo.Constructor, - Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Call(rowExp, Utils.MethodDataReaderGetValue, dataIndexExp)), - //Expression.Call(Utils.MethodGetDataReaderValue, new Expression[] { Expression.Constant(prop.PropertyType), Expression.Call(rowExp, Utils.MethodDataReaderGetValue, dataIndexExp) }), - Expression.Add(dataIndexExp, Expression.Constant(1)) - ); - else { - var proptypeGeneric = prop.PropertyType; - if (proptypeGeneric.IsNullableType()) proptypeGeneric = proptypeGeneric.GenericTypeArguments.First(); - if (proptypeGeneric.IsEnum || - Utils.dicExecuteArrayRowReadClassOrTuple.ContainsKey(proptypeGeneric)) readExpAssign = Expression.New(Utils.RowInfo.Constructor, - Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Call(rowExp, Utils.MethodDataReaderGetValue, dataIndexExp)), - //Expression.Call(Utils.MethodGetDataReaderValue, new Expression[] { Expression.Constant(prop.PropertyType), Expression.Call(rowExp, Utils.MethodDataReaderGetValue, dataIndexExp) }), - Expression.Add(dataIndexExp, Expression.Constant(1)) - ); - else { - var propLazyType = _commonUtils.GetTableByEntity(prop.PropertyType)?.TypeLazy ?? prop.PropertyType; - readExpAssign = Expression.Call(Utils.MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(null, typeof(string)), Expression.Constant(propLazyType), Expression.Constant(null, typeof(int[])), rowExp, dataIndexExp, Expression.Constant(_commonUtils) }); - } - } - blockExp.AddRange(new Expression[] { - Expression.Assign(readExp, readExpAssign), - Expression.IfThen(Expression.GreaterThan(readExpDataIndex, dataIndexExp), - Expression.Assign(dataIndexExp, readExpDataIndex)), + if (tb.Table.ColumnsByCs.TryGetValue(prop.Name, out var col)) + { //普通字段 + if (index > 0) field.Append(", "); + var quoteName = _commonUtils.QuoteSqlName(col.Attribute.Name); + field.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"{tb.Alias}.{quoteName}")); + ++index; + if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); + else dicfield.Add(quoteName, true); + } + else + { + var tb2 = _tables.Where((a, b) => b > 0 && + (a.Type == SelectTableInfoType.InnerJoin || a.Type == SelectTableInfoType.LeftJoin || a.Type == SelectTableInfoType.RightJoin) && + string.IsNullOrEmpty(a.On) == false && + a.Alias.StartsWith($"{tb.Alias}__") && //开头结尾完全匹配 + a.Alias.EndsWith($"__{prop.Name}") //不清楚会不会有其他情况 求大佬优化 + ).FirstOrDefault(); //判断 b > 0 防止 parent 递归关系 + if (tb2 == null && props.Where(pw => pw.Value.PropertyType == prop.PropertyType).Count() == 1) + tb2 = _tables.Where((a, b) => b > 0 && + (a.Type == SelectTableInfoType.InnerJoin || a.Type == SelectTableInfoType.LeftJoin || a.Type == SelectTableInfoType.RightJoin) && + string.IsNullOrEmpty(a.On) == false && + a.Table.Type == prop.PropertyType).FirstOrDefault(); + if (tb2 == null) continue; + foreach (var col2 in tb2.Table.Columns.Values) + { + if (index > 0) field.Append(", "); + var quoteName = _commonUtils.QuoteSqlName(col2.Attribute.Name); + field.Append(_commonUtils.QuoteReadColumn(col2.Attribute.MapType, $"{tb2.Alias}.{quoteName}")); + ++index; + ++otherindex; + if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); + else dicfield.Add(quoteName, true); + } + } + //只读到二级属性 + var propGetSetMethod = prop.GetSetMethod(); + Expression readExpAssign = null; //加速缓存 + if (prop.PropertyType.IsArray) readExpAssign = Expression.New(Utils.RowInfo.Constructor, + Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Call(rowExp, Utils.MethodDataReaderGetValue, dataIndexExp)), + //Expression.Call(Utils.MethodGetDataReaderValue, new Expression[] { Expression.Constant(prop.PropertyType), Expression.Call(rowExp, Utils.MethodDataReaderGetValue, dataIndexExp) }), + Expression.Add(dataIndexExp, Expression.Constant(1)) + ); + else + { + var proptypeGeneric = prop.PropertyType; + if (proptypeGeneric.IsNullableType()) proptypeGeneric = proptypeGeneric.GenericTypeArguments.First(); + if (proptypeGeneric.IsEnum || + Utils.dicExecuteArrayRowReadClassOrTuple.ContainsKey(proptypeGeneric)) readExpAssign = Expression.New(Utils.RowInfo.Constructor, + Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Call(rowExp, Utils.MethodDataReaderGetValue, dataIndexExp)), + //Expression.Call(Utils.MethodGetDataReaderValue, new Expression[] { Expression.Constant(prop.PropertyType), Expression.Call(rowExp, Utils.MethodDataReaderGetValue, dataIndexExp) }), + Expression.Add(dataIndexExp, Expression.Constant(1)) + ); + else + { + var propLazyType = _commonUtils.GetTableByEntity(prop.PropertyType)?.TypeLazy ?? prop.PropertyType; + readExpAssign = Expression.Call(Utils.MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(null, typeof(string)), Expression.Constant(propLazyType), Expression.Constant(null, typeof(int[])), rowExp, dataIndexExp, Expression.Constant(_commonUtils) }); + } + } + blockExp.AddRange(new Expression[] { + Expression.Assign(readExp, readExpAssign), + Expression.IfThen(Expression.GreaterThan(readExpDataIndex, dataIndexExp), + Expression.Assign(dataIndexExp, readExpDataIndex)), //Expression.Call(typeof(Trace).GetMethod("WriteLine", new Type[]{typeof(string)}), Expression.Call(typeof(string).GetMethod("Concat", new Type[]{typeof(object) }), readExpValue)), tb1.TypeLazy != null ? - Expression.IfThenElse( - Expression.NotEqual(readExpValue, Expression.Constant(null)), - Expression.Call(retExp, propGetSetMethod, Expression.Convert(readExpValue, prop.PropertyType)), - Expression.Call(retExp, propGetSetMethod, Expression.Convert(Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Constant(null)), prop.PropertyType)) - ) : - Expression.IfThen( - Expression.NotEqual(readExpValue, Expression.Constant(null)), - Expression.Call(retExp, propGetSetMethod, Expression.Convert(readExpValue, prop.PropertyType)) - ) - }); - } - if (otherindex == 0) { //不读导航属性,优化单表读取性能 - blockExp.Clear(); - blockExp.AddRange(new Expression[] { - Expression.Assign(dataIndexExp, Expression.Constant(0)), - Expression.Assign(readExp, Expression.Call(Utils.MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(null, typeof(string)), Expression.Constant(type), Expression.Constant(null, typeof(int[])), rowExp, dataIndexExp, Expression.Constant(_commonUtils) })), - Expression.IfThen( - Expression.NotEqual(readExpValue, Expression.Constant(null)), - Expression.Assign(retExp, Expression.Convert(readExpValue, type)) - ) - }); - } - if (tb1.TypeLazy != null) - blockExp.Add( - Expression.IfThen( - Expression.NotEqual(readExpValue, Expression.Constant(null)), - Expression.Call(retExp, tb1.TypeLazySetOrm, ormExp) - ) - ); //将 orm 传递给 lazy - blockExp.AddRange(new Expression[] { - Expression.Return(returnTarget, retExp), - Expression.Label(returnTarget, Expression.Default(type)) - }); - return new GetAllFieldExpressionTreeInfo { - Field = field.ToString(), - Read = Expression.Lambda>(Expression.Block(new[] { retExp, dataIndexExp, readExp }, blockExp), new[] { ormExp, rowExp }).Compile() - }; - }); - } - protected (ReadAnonymousTypeInfo map, string field) GetAllFieldReflection() { - var tb1 = _tables.First().Table; - var type = tb1.Type; - var constructor = _dicConstructor.GetOrAdd(type, s => type.GetConstructor(new Type[0])); - var map = new ReadAnonymousTypeInfo { Consturctor = constructor, ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties }; + Expression.IfThenElse( + Expression.NotEqual(readExpValue, Expression.Constant(null)), + Expression.Call(retExp, propGetSetMethod, Expression.Convert(readExpValue, prop.PropertyType)), + Expression.Call(retExp, propGetSetMethod, Expression.Convert(Utils.GetDataReaderValueBlockExpression(prop.PropertyType, Expression.Constant(null)), prop.PropertyType)) + ) : + Expression.IfThen( + Expression.NotEqual(readExpValue, Expression.Constant(null)), + Expression.Call(retExp, propGetSetMethod, Expression.Convert(readExpValue, prop.PropertyType)) + ) + }); + } + if (otherindex == 0) + { //不读导航属性,优化单表读取性能 + blockExp.Clear(); + blockExp.AddRange(new Expression[] { + Expression.Assign(dataIndexExp, Expression.Constant(0)), + Expression.Assign(readExp, Expression.Call(Utils.MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(null, typeof(string)), Expression.Constant(type), Expression.Constant(null, typeof(int[])), rowExp, dataIndexExp, Expression.Constant(_commonUtils) })), + Expression.IfThen( + Expression.NotEqual(readExpValue, Expression.Constant(null)), + Expression.Assign(retExp, Expression.Convert(readExpValue, type)) + ) + }); + } + if (tb1.TypeLazy != null) + blockExp.Add( + Expression.IfThen( + Expression.NotEqual(readExpValue, Expression.Constant(null)), + Expression.Call(retExp, tb1.TypeLazySetOrm, ormExp) + ) + ); //将 orm 传递给 lazy + blockExp.AddRange(new Expression[] { + Expression.Return(returnTarget, retExp), + Expression.Label(returnTarget, Expression.Default(type)) + }); + return new GetAllFieldExpressionTreeInfo + { + Field = field.ToString(), + Read = Expression.Lambda>(Expression.Block(new[] { retExp, dataIndexExp, readExp }, blockExp), new[] { ormExp, rowExp }).Compile() + }; + }); + } + protected (ReadAnonymousTypeInfo map, string field) GetAllFieldReflection() + { + var tb1 = _tables.First().Table; + var type = tb1.Type; + var constructor = _dicConstructor.GetOrAdd(type, s => type.GetConstructor(new Type[0])); + var map = new ReadAnonymousTypeInfo { Consturctor = constructor, ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties }; - var field = new StringBuilder(); - var dicfield = new Dictionary(); - var tb = _tables.First(); - var index = 0; - var ps = tb1.Properties; - foreach (var p in ps.Values) { - var child = new ReadAnonymousTypeInfo { Property = p, CsName = p.Name }; - if (tb.Table.ColumnsByCs.TryGetValue(p.Name, out var col)) { //普通字段 - if (index > 0) field.Append(", "); - var quoteName = _commonUtils.QuoteSqlName(col.Attribute.Name); - field.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"{tb.Alias}.{quoteName}")); - ++index; - if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); - else dicfield.Add(quoteName, true); - } else { - var tb2 = _tables.Where(a => a.Table.Type == p.PropertyType && a.Alias.Contains(p.Name)).FirstOrDefault(); - if (tb2 == null && ps.Where(pw => pw.Value.PropertyType == p.PropertyType).Count() == 1) tb2 = _tables.Where(a => a.Table.Type == p.PropertyType).FirstOrDefault(); - if (tb2 == null) continue; - child.Consturctor = tb2.Table.Type.GetConstructor(new Type[0]); - child.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; - foreach (var col2 in tb2.Table.Columns.Values) { - if (index > 0) field.Append(", "); - var quoteName = _commonUtils.QuoteSqlName(col2.Attribute.Name); - field.Append(_commonUtils.QuoteReadColumn(col2.Attribute.MapType, $"{tb2.Alias}.{quoteName}")); - ++index; - if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); - else dicfield.Add(quoteName, true); - child.Childs.Add(new ReadAnonymousTypeInfo { - Property = tb2.Table.Type.GetProperty(col2.CsName, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance), - CsName = col2.CsName - }); - } - } - map.Childs.Add(child); - } - return (map, field.ToString()); - } + var field = new StringBuilder(); + var dicfield = new Dictionary(); + var tb = _tables.First(); + var index = 0; + var ps = tb1.Properties; + foreach (var p in ps.Values) + { + var child = new ReadAnonymousTypeInfo { Property = p, CsName = p.Name }; + if (tb.Table.ColumnsByCs.TryGetValue(p.Name, out var col)) + { //普通字段 + if (index > 0) field.Append(", "); + var quoteName = _commonUtils.QuoteSqlName(col.Attribute.Name); + field.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"{tb.Alias}.{quoteName}")); + ++index; + if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); + else dicfield.Add(quoteName, true); + } + else + { + var tb2 = _tables.Where(a => a.Table.Type == p.PropertyType && a.Alias.Contains(p.Name)).FirstOrDefault(); + if (tb2 == null && ps.Where(pw => pw.Value.PropertyType == p.PropertyType).Count() == 1) tb2 = _tables.Where(a => a.Table.Type == p.PropertyType).FirstOrDefault(); + if (tb2 == null) continue; + child.Consturctor = tb2.Table.Type.GetConstructor(new Type[0]); + child.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; + foreach (var col2 in tb2.Table.Columns.Values) + { + if (index > 0) field.Append(", "); + var quoteName = _commonUtils.QuoteSqlName(col2.Attribute.Name); + field.Append(_commonUtils.QuoteReadColumn(col2.Attribute.MapType, $"{tb2.Alias}.{quoteName}")); + ++index; + if (dicfield.ContainsKey(quoteName)) field.Append(" as").Append(index); + else dicfield.Add(quoteName, true); + child.Childs.Add(new ReadAnonymousTypeInfo + { + Property = tb2.Table.Type.GetProperty(col2.CsName, BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance), + CsName = col2.CsName + }); + } + } + map.Childs.Add(child); + } + return (map, field.ToString()); + } - protected string TableRuleInvoke(Type type, string oldname) { - for (var a = _tableRules.Count - 1; a >= 0; a--) { - var newname = _tableRules[a]?.Invoke(type, oldname); - if (!string.IsNullOrEmpty(newname)) return newname; - } - return oldname; - } + protected string TableRuleInvoke(Type type, string oldname) + { + for (var a = _tableRules.Count - 1; a >= 0; a--) + { + var newname = _tableRules[a]?.Invoke(type, oldname); + if (!string.IsNullOrEmpty(newname)) return newname; + } + return oldname; + } - public TSelect AsTable(Func tableRule) { - if (tableRule != null) _tableRules.Add(tableRule); - return this as TSelect; - } - public TSelect AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object"); - if (entityType == _tables[0].Table.Type) return this as TSelect; - var newtb = _commonUtils.GetTableByEntity(entityType); - _tables[0].Table = newtb ?? throw new Exception("ISelect.AsType 参数错误,请传入正确的实体类型"); - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); - return this as TSelect; - } - public abstract string ToSql(string field = null); + public TSelect AsTable(Func tableRule) + { + if (tableRule != null) _tableRules.Add(tableRule); + return this as TSelect; + } + public TSelect AsType(Type entityType) + { + if (entityType == typeof(object)) throw new Exception("ISelect.AsType 参数不支持指定为 object"); + if (entityType == _tables[0].Table.Type) return this as TSelect; + var newtb = _commonUtils.GetTableByEntity(entityType); + _tables[0].Table = newtb ?? throw new Exception("ISelect.AsType 参数错误,请传入正确的实体类型"); + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); + return this as TSelect; + } + public abstract string ToSql(string field = null); - public TSelect Where(string sql, object parms = null) => this.WhereIf(true, sql, parms); - public TSelect WhereIf(bool condition, string sql, object parms = null) { - if (condition == false || string.IsNullOrEmpty(sql)) return this as TSelect; - var args = new Aop.WhereEventArgs(sql, parms); - _orm.Aop.Where?.Invoke(this, new Aop.WhereEventArgs(sql, parms)); - if (args.IsCancel == true) return this as TSelect; + public TSelect Where(string sql, object parms = null) => this.WhereIf(true, sql, parms); + public TSelect WhereIf(bool condition, string sql, object parms = null) + { + if (condition == false || string.IsNullOrEmpty(sql)) return this as TSelect; + var args = new Aop.WhereEventArgs(sql, parms); + _orm.Aop.Where?.Invoke(this, new Aop.WhereEventArgs(sql, parms)); + if (args.IsCancel == true) return this as TSelect; - _where.Append(" AND (").Append(sql).Append(")"); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this as TSelect; - } - #region common + _where.Append(" AND (").Append(sql).Append(")"); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this as TSelect; + } + #region common - protected TMember InternalAvg(Expression exp) => this.ToList($"avg({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})").FirstOrDefault(); - async protected Task InternalAvgAsync(Expression exp) => (await this.ToListAsync($"avg({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})")).FirstOrDefault(); - protected TMember InternalMax(Expression exp) => this.ToList($"max({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})").FirstOrDefault(); - async protected Task InternalMaxAsync(Expression exp) => (await this.ToListAsync($"max({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})")).FirstOrDefault(); - protected TMember InternalMin(Expression exp) => this.ToList($"min({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})").FirstOrDefault(); - async protected Task InternalMinAsync(Expression exp) => (await this.ToListAsync($"min({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})")).FirstOrDefault(); - protected TMember InternalSum(Expression exp) => this.ToList($"sum({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})").FirstOrDefault(); - async protected Task InternalSumAsync(Expression exp) => (await this.ToListAsync($"sum({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})")).FirstOrDefault(); + protected TMember InternalAvg(Expression exp) => this.ToList($"avg({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})").FirstOrDefault(); + async protected Task InternalAvgAsync(Expression exp) => (await this.ToListAsync($"avg({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})")).FirstOrDefault(); + protected TMember InternalMax(Expression exp) => this.ToList($"max({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})").FirstOrDefault(); + async protected Task InternalMaxAsync(Expression exp) => (await this.ToListAsync($"max({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})")).FirstOrDefault(); + protected TMember InternalMin(Expression exp) => this.ToList($"min({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})").FirstOrDefault(); + async protected Task InternalMinAsync(Expression exp) => (await this.ToListAsync($"min({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})")).FirstOrDefault(); + protected TMember InternalSum(Expression exp) => this.ToList($"sum({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})").FirstOrDefault(); + async protected Task InternalSumAsync(Expression exp) => (await this.ToListAsync($"sum({_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, exp, true, null)})")).FirstOrDefault(); - protected ISelectGrouping InternalGroupBy(Expression columns) { - var map = new ReadAnonymousTypeInfo(); - var field = new StringBuilder(); - var index = -10000; //临时规则,不返回 as1 + protected ISelectGrouping InternalGroupBy(Expression columns) + { + var map = new ReadAnonymousTypeInfo(); + var field = new StringBuilder(); + var index = -10000; //临时规则,不返回 as1 - _commonExpression.ReadAnonymousField(_tables, field, map, ref index, columns, null); - this.GroupBy(field.Length > 0 ? field.Remove(0, 2).ToString() : null); - return new SelectGroupingProvider(this, map, _commonExpression, _tables); - } - protected TSelect InternalJoin(Expression exp, SelectTableInfoType joinType) { - _commonExpression.ExpressionJoinLambda(_tables, joinType, exp, null); - return this as TSelect; - } - protected TSelect InternalJoin(Expression exp, SelectTableInfoType joinType) { - var tb = _commonUtils.GetTableByEntity(typeof(T2)); - if (tb == null) throw new ArgumentException("T2 类型错误"); - _tables.Add(new SelectTableInfo { Table = tb, Alias = $"IJ{_tables.Count}", On = null, Type = joinType }); - _commonExpression.ExpressionJoinLambda(_tables, joinType, exp, null); - return this as TSelect; - } - protected TSelect InternalOrderBy(Expression column) => this.OrderBy(_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, column, true, null)); - protected TSelect InternalOrderByDescending(Expression column) => this.OrderBy($"{_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, column, true, null)} DESC"); + _commonExpression.ReadAnonymousField(_tables, field, map, ref index, columns, null); + this.GroupBy(field.Length > 0 ? field.Remove(0, 2).ToString() : null); + return new SelectGroupingProvider(this, map, _commonExpression, _tables); + } + protected TSelect InternalJoin(Expression exp, SelectTableInfoType joinType) + { + _commonExpression.ExpressionJoinLambda(_tables, joinType, exp, null); + return this as TSelect; + } + protected TSelect InternalJoin(Expression exp, SelectTableInfoType joinType) + { + var tb = _commonUtils.GetTableByEntity(typeof(T2)); + if (tb == null) throw new ArgumentException("T2 类型错误"); + _tables.Add(new SelectTableInfo { Table = tb, Alias = $"IJ{_tables.Count}", On = null, Type = joinType }); + _commonExpression.ExpressionJoinLambda(_tables, joinType, exp, null); + return this as TSelect; + } + protected TSelect InternalOrderBy(Expression column) => this.OrderBy(_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, column, true, null)); + protected TSelect InternalOrderByDescending(Expression column) => this.OrderBy($"{_commonExpression.ExpressionSelectColumn_MemberAccess(_tables, null, SelectTableInfoType.From, column, true, null)} DESC"); - protected List InternalToList(Expression select) => this.ToListMapReader(this.GetExpressionField(select)); - protected Task> InternalToListAsync(Expression select) => this.ToListMapReaderAsync(this.GetExpressionField(select)); - protected string InternalToSql(Expression select) { - var af = this.GetExpressionField(select); - return this.ToSql(af.field); - } + protected List InternalToList(Expression select) => this.ToListMapReader(this.GetExpressionField(select)); + protected Task> InternalToListAsync(Expression select) => this.ToListMapReaderAsync(this.GetExpressionField(select)); + protected string InternalToSql(Expression select) + { + var af = this.GetExpressionField(select); + return this.ToSql(af.field); + } - protected DataTable InternalToDataTable(Expression select) { - var sql = this.InternalToSql(select); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - DataTable ret = null; - Exception exception = null; - try { - ret = _orm.Ado.ExecuteDataTable(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - return ret; - } - async protected Task InternalToDataTableAsync(Expression select) { - var sql = this.InternalToSql(select); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - DataTable ret = null; - Exception exception = null; - try { - ret = await _orm.Ado.ExecuteDataTableAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - return ret; - } + protected DataTable InternalToDataTable(Expression select) + { + var sql = this.InternalToSql(select); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + DataTable ret = null; + Exception exception = null; + try + { + ret = _orm.Ado.ExecuteDataTable(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + return ret; + } + async protected Task InternalToDataTableAsync(Expression select) + { + var sql = this.InternalToSql(select); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_tables[0].Table.Type, Aop.CurdType.Select, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + DataTable ret = null; + Exception exception = null; + try + { + ret = await _orm.Ado.ExecuteDataTableAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + return ret; + } - protected TReturn InternalToAggregate(Expression select) { - var map = new ReadAnonymousTypeInfo(); - var field = new StringBuilder(); - var index = 0; + protected TReturn InternalToAggregate(Expression select) + { + var map = new ReadAnonymousTypeInfo(); + var field = new StringBuilder(); + var index = 0; - _commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null); - return this.ToListMapReader((map, field.Length > 0 ? field.Remove(0, 2).ToString() : null)).FirstOrDefault(); - } - async protected Task InternalToAggregateAsync(Expression select) { - var map = new ReadAnonymousTypeInfo(); - var field = new StringBuilder(); - var index = 0; + _commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null); + return this.ToListMapReader((map, field.Length > 0 ? field.Remove(0, 2).ToString() : null)).FirstOrDefault(); + } + async protected Task InternalToAggregateAsync(Expression select) + { + var map = new ReadAnonymousTypeInfo(); + var field = new StringBuilder(); + var index = 0; - _commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null); - return (await this.ToListMapReaderAsync((map, field.Length > 0 ? field.Remove(0, 2).ToString() : null))).FirstOrDefault(); - } + _commonExpression.ReadAnonymousField(_tables, field, map, ref index, select, null); + return (await this.ToListMapReaderAsync((map, field.Length > 0 ? field.Remove(0, 2).ToString() : null))).FirstOrDefault(); + } - protected TSelect InternalWhere(Expression exp) => exp == null ? this as TSelect : this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp, null)); - - protected TSelect InternalJoin(Expression exp) { - return this as TSelect; - } - #endregion - } + protected TSelect InternalWhere(Expression exp) => exp == null ? this as TSelect : this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp, null)); + #endregion + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select10Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select10Provider.cs index efb1af06..a2e67382 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select10Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select10Provider.cs @@ -5,178 +5,204 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select10Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class - where T3 : class - where T4 : class - where T5 : class - where T6 : class - where T7 : class - where T8 : class - where T9 : class - where T10 : class { + public abstract class Select10Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + where T3 : class + where T4 : class + where T5 : class + where T6 : class + where T7 : class + where T8 : class + where T9 : class + where T10 : class + { - public Select10Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T7)), Alias = $"SP10g", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T8)), Alias = $"SP10h", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T9)), Alias = $"SP10i", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T10)), Alias = $"SP10j", On = null, Type = SelectTableInfoType.From }); - } + public Select10Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9), typeof(T10)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T7)), Alias = $"SP10g", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T8)), Alias = $"SP10h", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T9)), Alias = $"SP10i", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T10)), Alias = $"SP10j", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy (exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b"), - Expression.Parameter(typeof(T3), "c"), - Expression.Parameter(typeof(T4), "d"), - Expression.Parameter(typeof(T5), "e"), - Expression.Parameter(typeof(T6), "f"), - Expression.Parameter(typeof(T7), "g"), - Expression.Parameter(typeof(T8), "h"), - Expression.Parameter(typeof(T9), "i"), - Expression.Parameter(typeof(T10), "j")); - } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b"), + Expression.Parameter(typeof(T3), "c"), + Expression.Parameter(typeof(T4), "d"), + Expression.Parameter(typeof(T5), "e"), + Expression.Parameter(typeof(T6), "f"), + Expression.Parameter(typeof(T7), "g"), + Expression.Parameter(typeof(T8), "h"), + Expression.Parameter(typeof(T9), "i"), + Expression.Parameter(typeof(T10), "j")); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return condition ? this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)) : this; - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return condition ? this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)) : this; + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs index 0f2ee90e..5885b69e 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select1Provider.cs @@ -14,784 +14,911 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select1Provider : Select0Provider, T1>, ISelect - where T1 : class { - public Select1Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { + public abstract class Select1Provider : Select0Provider, T1>, ISelect + where T1 : class + { + public Select1Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { - } + } - protected ISelect InternalFrom(Expression exp) { - if (exp.NodeType == ExpressionType.Call) { - var expCall = exp as MethodCallExpression; - var stockCall = new Stack(); - while (expCall != null) { - stockCall.Push(expCall); - expCall = expCall.Object as MethodCallExpression; - } - while (stockCall.Any()) { - expCall = stockCall.Pop(); + protected ISelect InternalFrom(Expression exp) + { + if (exp.NodeType == ExpressionType.Call) + { + var expCall = exp as MethodCallExpression; + var stockCall = new Stack(); + while (expCall != null) + { + stockCall.Push(expCall); + expCall = expCall.Object as MethodCallExpression; + } + while (stockCall.Any()) + { + expCall = stockCall.Pop(); - switch (expCall.Method.Name) { - case "Where": this.InternalWhere(expCall.Arguments[0]); break; - case "WhereIf": - var whereIfCond = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, expCall.Arguments[0], false, null); - if (whereIfCond == "1" || whereIfCond == "'t'") - this.InternalWhere(expCall.Arguments[1]); - break; - case "OrderBy": - if (expCall.Arguments.Count == 2 && expCall.Arguments[0].Type == typeof(bool)) { - var ifcond = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, expCall.Arguments[0], false, null); - if (ifcond == "1" || ifcond == "'t'") - this.InternalOrderBy(expCall.Arguments.LastOrDefault()); - break; - } - this.InternalOrderBy(expCall.Arguments.LastOrDefault()); - break; - case "OrderByDescending": - if (expCall.Arguments.Count == 2 && expCall.Arguments[0].Type == typeof(bool)) { - var ifcond = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, expCall.Arguments[0], false, null); - if (ifcond == "1" || ifcond == "'t'") - this.InternalOrderByDescending(expCall.Arguments.LastOrDefault()); - break; - } - this.InternalOrderByDescending(expCall.Arguments.LastOrDefault()); - break; + switch (expCall.Method.Name) + { + case "Where": this.InternalWhere(expCall.Arguments[0]); break; + case "WhereIf": + var whereIfCond = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, expCall.Arguments[0], false, null); + if (whereIfCond == "1" || whereIfCond == "'t'") + this.InternalWhere(expCall.Arguments[1]); + break; + case "OrderBy": + if (expCall.Arguments.Count == 2 && expCall.Arguments[0].Type == typeof(bool)) + { + var ifcond = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, expCall.Arguments[0], false, null); + if (ifcond == "1" || ifcond == "'t'") + this.InternalOrderBy(expCall.Arguments.LastOrDefault()); + break; + } + this.InternalOrderBy(expCall.Arguments.LastOrDefault()); + break; + case "OrderByDescending": + if (expCall.Arguments.Count == 2 && expCall.Arguments[0].Type == typeof(bool)) + { + var ifcond = _commonExpression.ExpressionSelectColumn_MemberAccess(null, null, SelectTableInfoType.From, expCall.Arguments[0], false, null); + if (ifcond == "1" || ifcond == "'t'") + this.InternalOrderByDescending(expCall.Arguments.LastOrDefault()); + break; + } + this.InternalOrderByDescending(expCall.Arguments.LastOrDefault()); + break; - case "LeftJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.LeftJoin); break; - case "InnerJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.InnerJoin); break; - case "RightJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.RightJoin); break; + case "LeftJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.LeftJoin); break; + case "InnerJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.InnerJoin); break; + case "RightJoin": this.InternalJoin(expCall.Arguments[0], SelectTableInfoType.RightJoin); break; - default: throw new NotImplementedException($"未实现 {expCall.Method.Name}"); - } - } - } - return this; - } + default: throw new NotImplementedException($"未实现 {expCall.Method.Name}"); + } + } + } + return this; + } - public ISelect As(string alias) { - var oldAs = _tables.First().Alias; - var newAs = string.IsNullOrEmpty(alias) ? "a" : alias; - if (oldAs != newAs) { - _tables.First().Alias = newAs; - var wh = _where.ToString(); - _where.Replace($" {oldAs}.", $" {newAs}."); - } - return this; - } + public ISelect As(string alias) + { + var oldAs = _tables.First().Alias; + var newAs = string.IsNullOrEmpty(alias) ? "a" : alias; + if (oldAs != newAs) + { + _tables.First().Alias = newAs; + var wh = _where.ToString(); + _where.Replace($" {oldAs}.", $" {newAs}."); + } + return this; + } - public TMember Avg(Expression> column) { - if (column == null) return default(TMember); - _tables[0].Parameter = column.Parameters[0]; - return this.InternalAvg(column?.Body); - } - public Task AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - _tables[0].Parameter = column.Parameters[0]; - return this.InternalAvgAsync(column?.Body); - } + public TMember Avg(Expression> column) + { + if (column == null) return default(TMember); + _tables[0].Parameter = column.Parameters[0]; + return this.InternalAvg(column?.Body); + } + public Task AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + _tables[0].Parameter = column.Parameters[0]; + return this.InternalAvgAsync(column?.Body); + } - public abstract ISelect From(Expression, T2, ISelectFromExpression>> exp) where T2 : class;// { this.InternalFrom(exp?.Body); var ret = new Select3Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public abstract ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) where T2 : class where T3 : class;// { this.InternalFrom(exp?.Body); var ret = new Select3Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public abstract ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class;// { this.InternalFrom(exp?.Body); var ret = new Select4Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public abstract ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class;// { this.InternalFrom(exp?.Body); var ret = new Select5Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public abstract ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class;// { this.InternalFrom(exp?.Body); var ret = new Select6Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class;// { this.InternalFrom(exp?.Body); var ret = new Select7Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class;// { this.InternalFrom(exp?.Body); var ret = new Select8Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class;// { this.InternalFrom(exp?.Body); var ret = new Select9Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class;// { this.InternalFrom(exp?.Body); var ret = new Select10Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, ISelectFromExpression>> exp) where T2 : class;// { this.InternalFrom(exp?.Body); var ret = new Select3Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) where T2 : class where T3 : class;// { this.InternalFrom(exp?.Body); var ret = new Select3Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class;// { this.InternalFrom(exp?.Body); var ret = new Select4Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class;// { this.InternalFrom(exp?.Body); var ret = new Select5Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class;// { this.InternalFrom(exp?.Body); var ret = new Select6Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class;// { this.InternalFrom(exp?.Body); var ret = new Select7Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class;// { this.InternalFrom(exp?.Body); var ret = new Select8Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class;// { this.InternalFrom(exp?.Body); var ret = new Select9Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } + public abstract ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class;// { this.InternalFrom(exp?.Body); var ret = new Select10Provider(_orm, _commonUtils, _commonExpression, null); Select0Provider, T1>.CopyData(this, ret, exp?.Parameters); return ret; } - public ISelectGrouping GroupBy(Expression> columns) { - if (columns == null) return this.InternalGroupBy(columns); - _tables[0].Parameter = columns.Parameters[0]; - return this.InternalGroupBy(columns); - } + public ISelectGrouping GroupBy(Expression> columns) + { + if (columns == null) return this.InternalGroupBy(columns); + _tables[0].Parameter = columns.Parameters[0]; + return this.InternalGroupBy(columns); + } - public TMember Max(Expression> column) { - if (column == null) return default(TMember); - _tables[0].Parameter = column.Parameters[0]; - return this.InternalMax(column?.Body); - } - public Task MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - _tables[0].Parameter = column.Parameters[0]; - return this.InternalMaxAsync(column?.Body); - } + public TMember Max(Expression> column) + { + if (column == null) return default(TMember); + _tables[0].Parameter = column.Parameters[0]; + return this.InternalMax(column?.Body); + } + public Task MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + _tables[0].Parameter = column.Parameters[0]; + return this.InternalMaxAsync(column?.Body); + } - public TMember Min(Expression> column) { - if (column == null) return default(TMember); - _tables[0].Parameter = column.Parameters[0]; - return this.InternalMin(column?.Body); - } - public Task MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - _tables[0].Parameter = column.Parameters[0]; - return this.InternalMinAsync(column?.Body); - } - public ISelect OrderBy(Expression> column) => this.OrderBy(true, column); - public ISelect OrderBy(bool condition, Expression> column) { - if (condition == false || column == null) return this; - _tables[0].Parameter = column.Parameters[0]; - return this.InternalOrderBy(column?.Body); - } - public ISelect OrderByDescending(Expression> column) => this.OrderByDescending(true, column); - public ISelect OrderByDescending(bool condition, Expression> column) { - if (condition == false || column == null) return this; - _tables[0].Parameter = column.Parameters[0]; - return this.InternalOrderByDescending(column?.Body); - } + public TMember Min(Expression> column) + { + if (column == null) return default(TMember); + _tables[0].Parameter = column.Parameters[0]; + return this.InternalMin(column?.Body); + } + public Task MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + _tables[0].Parameter = column.Parameters[0]; + return this.InternalMinAsync(column?.Body); + } + public ISelect OrderBy(Expression> column) => this.OrderBy(true, column); + public ISelect OrderBy(bool condition, Expression> column) + { + if (condition == false || column == null) return this; + _tables[0].Parameter = column.Parameters[0]; + return this.InternalOrderBy(column?.Body); + } + public ISelect OrderByDescending(Expression> column) => this.OrderByDescending(true, column); + public ISelect OrderByDescending(bool condition, Expression> column) + { + if (condition == false || column == null) return this; + _tables[0].Parameter = column.Parameters[0]; + return this.InternalOrderByDescending(column?.Body); + } - public TMember Sum(Expression> column) { - if (column == null) return default(TMember); - _tables[0].Parameter = column.Parameters[0]; - return this.InternalSum(column?.Body); - } - public Task SumAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - _tables[0].Parameter = column.Parameters[0]; - return this.InternalSumAsync(column?.Body); - } + public TMember Sum(Expression> column) + { + if (column == null) return default(TMember); + _tables[0].Parameter = column.Parameters[0]; + return this.InternalSum(column?.Body); + } + public Task SumAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + _tables[0].Parameter = column.Parameters[0]; + return this.InternalSumAsync(column?.Body); + } - public List ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - _tables[0].Parameter = select.Parameters[0]; - return this.InternalToList(select?.Body); - } - public Task> ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - _tables[0].Parameter = select.Parameters[0]; - return this.InternalToListAsync(select?.Body); - } - public List ToList() => ToList(GetToListDtoSelector()); - public Task> ToListAsync() => ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a")); - } + public List ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + _tables[0].Parameter = select.Parameters[0]; + return this.InternalToList(select?.Body); + } + public Task> ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + _tables[0].Parameter = select.Parameters[0]; + return this.InternalToListAsync(select?.Body); + } + public List ToList() => ToList(GetToListDtoSelector()); + public Task> ToListAsync() => ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a")); + } - #region linq to sql - public ISelect Select(Expression> select) where TReturn : class { - if (typeof(TReturn) == typeof(T1)) return this as ISelect; - _tables[0].Parameter = select.Parameters[0]; - _selectExpression = select.Body; - (_orm.CodeFirst as CodeFirstProvider).dicSyced.TryAdd(typeof(TReturn).FullName, true); - var ret = _orm.Select(); - Select0Provider, T1>.CopyData(this, ret, null); - return ret; - } - public ISelect Join(ISelect inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression> resultSelector) where TInner : class where TResult : class { - _tables[0].Parameter = resultSelector.Parameters[0]; - _commonExpression.ExpressionLambdaToSql(outerKeySelector, new CommonExpression.ExpTSC { _tables = _tables }); - this.InternalJoin(Expression.Lambda>( - Expression.Equal(outerKeySelector.Body, innerKeySelector.Body), - new[] { outerKeySelector.Parameters[0], innerKeySelector.Parameters[0] } - ), SelectTableInfoType.InnerJoin); - if (typeof(TResult) == typeof(T1)) return this as ISelect; - _selectExpression = resultSelector.Body; - (_orm.CodeFirst as CodeFirstProvider).dicSyced.TryAdd(typeof(TResult).FullName, true); - var ret = _orm.Select() as Select1Provider; - Select0Provider, T1>.CopyData(this, ret, null); - return ret; - } - public ISelect GroupJoin(ISelect inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression, TResult>> resultSelector) where TInner : class where TResult : class { - _tables[0].Parameter = resultSelector.Parameters[0]; - _commonExpression.ExpressionLambdaToSql(outerKeySelector, new CommonExpression.ExpTSC { _tables = _tables }); - this.InternalJoin(Expression.Lambda>( - Expression.Equal(outerKeySelector.Body, innerKeySelector.Body), - new[] { outerKeySelector.Parameters[0], innerKeySelector.Parameters[0] } - ), SelectTableInfoType.InnerJoin); - if (typeof(TResult) == typeof(T1)) return this as ISelect; - _selectExpression = resultSelector.Body; - (_orm.CodeFirst as CodeFirstProvider).dicSyced.TryAdd(typeof(TResult).FullName, true); - var ret = _orm.Select() as Select1Provider; - Select0Provider, T1>.CopyData(this, ret, null); - return ret; - } - public ISelect SelectMany(Expression>> collectionSelector, Expression> resultSelector) where TCollection : class where TResult : class { - SelectTableInfo find = null; - if (collectionSelector.Body.NodeType == ExpressionType.Call) { - var callExp = collectionSelector.Body as MethodCallExpression; - if (callExp.Method.Name == "DefaultIfEmpty" && callExp.Object.Type.GenericTypeArguments.Any()) { - find = _tables.Where((a, idx) => idx > 0 && a.Type == SelectTableInfoType.InnerJoin && a.Table.Type == callExp.Object.Type.GenericTypeArguments[0]).LastOrDefault(); - if (find != null) { - if (!string.IsNullOrEmpty(find.On)) find.On = Regex.Replace(find.On, $@"\b{find.Alias}\.", $"{resultSelector.Parameters[1].Name}."); - if (!string.IsNullOrEmpty(find.NavigateCondition)) find.NavigateCondition = Regex.Replace(find.NavigateCondition, $@"\b{find.Alias}\.", $"{resultSelector.Parameters[1].Name}."); - find.Type = SelectTableInfoType.LeftJoin; - find.Alias = resultSelector.Parameters[1].Name; - find.Parameter = resultSelector.Parameters[1]; - } - } - } - if (find == null) { - var tb = _commonUtils.GetTableByEntity(typeof(TCollection)); - if (tb == null) throw new Exception($"SelectMany 错误的类型:{typeof(TCollection).FullName}"); - _tables.Add(new SelectTableInfo { Alias = resultSelector.Parameters[1].Name, AliasInit = resultSelector.Parameters[1].Name, Parameter = resultSelector.Parameters[1], Table = tb, Type = SelectTableInfoType.From }); - } - if (typeof(TResult) == typeof(T1)) return this as ISelect; - _selectExpression = resultSelector.Body; - (_orm.CodeFirst as CodeFirstProvider).dicSyced.TryAdd(typeof(TResult).FullName, true); - var ret = _orm.Select() as Select1Provider; - Select0Provider, T1>.CopyData(this, ret, null); - return ret; - } - public ISelect DefaultIfEmpty() { - return this; - } - #endregion + #region linq to sql + public ISelect Select(Expression> select) where TReturn : class + { + if (typeof(TReturn) == typeof(T1)) return this as ISelect; + _tables[0].Parameter = select.Parameters[0]; + _selectExpression = select.Body; + (_orm.CodeFirst as CodeFirstProvider).dicSyced.TryAdd(typeof(TReturn).FullName, true); + var ret = _orm.Select(); + Select0Provider, T1>.CopyData(this, ret, null); + return ret; + } + public ISelect Join(ISelect inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression> resultSelector) where TInner : class where TResult : class + { + _tables[0].Parameter = resultSelector.Parameters[0]; + _commonExpression.ExpressionLambdaToSql(outerKeySelector, new CommonExpression.ExpTSC { _tables = _tables }); + this.InternalJoin(Expression.Lambda>( + Expression.Equal(outerKeySelector.Body, innerKeySelector.Body), + new[] { outerKeySelector.Parameters[0], innerKeySelector.Parameters[0] } + ), SelectTableInfoType.InnerJoin); + if (typeof(TResult) == typeof(T1)) return this as ISelect; + _selectExpression = resultSelector.Body; + (_orm.CodeFirst as CodeFirstProvider).dicSyced.TryAdd(typeof(TResult).FullName, true); + var ret = _orm.Select() as Select1Provider; + Select0Provider, T1>.CopyData(this, ret, null); + return ret; + } + public ISelect GroupJoin(ISelect inner, Expression> outerKeySelector, Expression> innerKeySelector, Expression, TResult>> resultSelector) where TInner : class where TResult : class + { + _tables[0].Parameter = resultSelector.Parameters[0]; + _commonExpression.ExpressionLambdaToSql(outerKeySelector, new CommonExpression.ExpTSC { _tables = _tables }); + this.InternalJoin(Expression.Lambda>( + Expression.Equal(outerKeySelector.Body, innerKeySelector.Body), + new[] { outerKeySelector.Parameters[0], innerKeySelector.Parameters[0] } + ), SelectTableInfoType.InnerJoin); + if (typeof(TResult) == typeof(T1)) return this as ISelect; + _selectExpression = resultSelector.Body; + (_orm.CodeFirst as CodeFirstProvider).dicSyced.TryAdd(typeof(TResult).FullName, true); + var ret = _orm.Select() as Select1Provider; + Select0Provider, T1>.CopyData(this, ret, null); + return ret; + } + public ISelect SelectMany(Expression>> collectionSelector, Expression> resultSelector) where TCollection : class where TResult : class + { + SelectTableInfo find = null; + if (collectionSelector.Body.NodeType == ExpressionType.Call) + { + var callExp = collectionSelector.Body as MethodCallExpression; + if (callExp.Method.Name == "DefaultIfEmpty" && callExp.Object.Type.GenericTypeArguments.Any()) + { + find = _tables.Where((a, idx) => idx > 0 && a.Type == SelectTableInfoType.InnerJoin && a.Table.Type == callExp.Object.Type.GenericTypeArguments[0]).LastOrDefault(); + if (find != null) + { + if (!string.IsNullOrEmpty(find.On)) find.On = Regex.Replace(find.On, $@"\b{find.Alias}\.", $"{resultSelector.Parameters[1].Name}."); + if (!string.IsNullOrEmpty(find.NavigateCondition)) find.NavigateCondition = Regex.Replace(find.NavigateCondition, $@"\b{find.Alias}\.", $"{resultSelector.Parameters[1].Name}."); + find.Type = SelectTableInfoType.LeftJoin; + find.Alias = resultSelector.Parameters[1].Name; + find.Parameter = resultSelector.Parameters[1]; + } + } + } + if (find == null) + { + var tb = _commonUtils.GetTableByEntity(typeof(TCollection)); + if (tb == null) throw new Exception($"SelectMany 错误的类型:{typeof(TCollection).FullName}"); + _tables.Add(new SelectTableInfo { Alias = resultSelector.Parameters[1].Name, AliasInit = resultSelector.Parameters[1].Name, Parameter = resultSelector.Parameters[1], Table = tb, Type = SelectTableInfoType.From }); + } + if (typeof(TResult) == typeof(T1)) return this as ISelect; + _selectExpression = resultSelector.Body; + (_orm.CodeFirst as CodeFirstProvider).dicSyced.TryAdd(typeof(TResult).FullName, true); + var ret = _orm.Select() as Select1Provider; + Select0Provider, T1>.CopyData(this, ret, null); + return ret; + } + public ISelect DefaultIfEmpty() + { + return this; + } + #endregion - public DataTable ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - _tables[0].Parameter = select.Parameters[0]; - return this.InternalToDataTable(select?.Body); - } + public DataTable ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + _tables[0].Parameter = select.Parameters[0]; + return this.InternalToDataTable(select?.Body); + } - public Task ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - _tables[0].Parameter = select.Parameters[0]; - return this.InternalToDataTableAsync(select?.Body); - } + public Task ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + _tables[0].Parameter = select.Parameters[0]; + return this.InternalToDataTableAsync(select?.Body); + } - public string ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - _tables[0].Parameter = select.Parameters[0]; - return this.InternalToSql(select?.Body); - } + public string ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + _tables[0].Parameter = select.Parameters[0]; + return this.InternalToSql(select?.Body); + } - public TReturn ToAggregate(Expression, TReturn>> select) { - if (select == null) return default(TReturn); - _tables[0].Parameter = select.Parameters[0]; - return this.InternalToAggregate(select?.Body); - } + public TReturn ToAggregate(Expression, TReturn>> select) + { + if (select == null) return default(TReturn); + _tables[0].Parameter = select.Parameters[0]; + return this.InternalToAggregate(select?.Body); + } - public Task ToAggregateAsync(Expression, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - _tables[0].Parameter = select.Parameters[0]; - return this.InternalToAggregateAsync(select?.Body); - } + public Task ToAggregateAsync(Expression, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + _tables[0].Parameter = select.Parameters[0]; + return this.InternalToAggregateAsync(select?.Body); + } - public ISelect Where(Expression> exp) { - if (exp == null) return this; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalWhere(exp?.Body); - } + public ISelect Where(Expression> exp) + { + if (exp == null) return this; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalWhere(exp?.Body); + } - public ISelect Where(Expression> exp) where T2 : class { - if (exp == null) return this; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalWhere(exp?.Body); - } + public ISelect Where(Expression> exp) where T2 : class + { + if (exp == null) return this; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalWhere(exp?.Body); + } - public ISelect Where(Expression> exp) where T2 : class { - if (exp == null) return this; - //_tables[0].Parameter = exp.Parameters[0]; - return this.InternalWhere(exp?.Body); - } + public ISelect Where(Expression> exp) where T2 : class + { + if (exp == null) return this; + //_tables[0].Parameter = exp.Parameters[0]; + return this.InternalWhere(exp?.Body); + } - public ISelect Where(Expression> exp) where T2 : class where T3 : class { - if (exp == null) return this; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalWhere(exp?.Body); - } + public ISelect Where(Expression> exp) where T2 : class where T3 : class + { + if (exp == null) return this; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalWhere(exp?.Body); + } - public ISelect Where(Expression> exp) where T2 : class where T3 : class where T4 : class { - if (exp == null) return this; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalWhere(exp?.Body); - } + public ISelect Where(Expression> exp) where T2 : class where T3 : class where T4 : class + { + if (exp == null) return this; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalWhere(exp?.Body); + } - public ISelect Where(Expression> exp) where T2 : class where T3 : class where T4 : class where T5 : class { - if (exp == null) return this; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalWhere(exp?.Body); - } - public ISelect WhereDynamic(object dywhere) => this.Where(_commonUtils.WhereObject(_tables.First().Table, $"{_tables.First().Alias}.", dywhere)); + public ISelect Where(Expression> exp) where T2 : class where T3 : class where T4 : class where T5 : class + { + if (exp == null) return this; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalWhere(exp?.Body); + } + public ISelect WhereDynamic(object dywhere) => this.Where(_commonUtils.WhereObject(_tables.First().Table, $"{_tables.First().Alias}.", dywhere)); - public ISelect WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - _tables[0].Parameter = exp.Parameters[0]; - return this.InternalWhere(exp?.Body); - } + public ISelect WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + _tables[0].Parameter = exp.Parameters[0]; + return this.InternalWhere(exp?.Body); + } - public bool Any(Expression> exp) => this.Where(exp).Any(); + public bool Any(Expression> exp) => this.Where(exp).Any(); - public Task AnyAsync(Expression> exp) => this.Where(exp).AnyAsync(); + public Task AnyAsync(Expression> exp) => this.Where(exp).AnyAsync(); - public TReturn ToOne(Expression> select) => this.Limit(1).ToList(select).FirstOrDefault(); + public TReturn ToOne(Expression> select) => this.Limit(1).ToList(select).FirstOrDefault(); - async public Task ToOneAsync(Expression> select) => (await this.Limit(1).ToListAsync(select)).FirstOrDefault(); + async public Task ToOneAsync(Expression> select) => (await this.Limit(1).ToListAsync(select)).FirstOrDefault(); - public TReturn First(Expression> select) => this.ToOne(select); + public TReturn First(Expression> select) => this.ToOne(select); - public Task FirstAsync(Expression> select) => this.ToOneAsync(select); + public Task FirstAsync(Expression> select) => this.ToOneAsync(select); - public ISelect Include(Expression> navigateSelector) where TNavigate : class { - var expBody = navigateSelector?.Body; - if (expBody == null) return this; - var tb = _commonUtils.GetTableByEntity(expBody.Type); - if (tb == null) throw new Exception("Include 参数类型错误"); + public ISelect Include(Expression> navigateSelector) where TNavigate : class + { + var expBody = navigateSelector?.Body; + if (expBody == null) return this; + var tb = _commonUtils.GetTableByEntity(expBody.Type); + if (tb == null) throw new Exception("Include 参数类型错误"); - _commonExpression.ExpressionWhereLambda(_tables, Expression.MakeMemberAccess(expBody, tb.Properties[tb.ColumnsByCs.First().Value.CsName]), null); - return this; - } + _commonExpression.ExpressionWhereLambda(_tables, Expression.MakeMemberAccess(expBody, tb.Properties[tb.ColumnsByCs.First().Value.CsName]), null); + return this; + } - static (ParameterExpression param, List members) GetExpressionStack(Expression exp) { - Expression tmpExp = exp; - ParameterExpression param = null; - var members = new List(); - var isbreak = false; - while (isbreak == false) { - switch (tmpExp.NodeType) { - case ExpressionType.MemberAccess: - var memExp = tmpExp as MemberExpression; - tmpExp = memExp.Expression; - members.Add(memExp); - continue; - case ExpressionType.Parameter: - param = tmpExp as ParameterExpression; - isbreak = true; - break; - default: - throw new Exception($"表达式错误,它不是连续的 MemberAccess 类型:{exp}"); - } - } - if (param == null) throw new Exception($"表达式错误,它的顶级对象不是 ParameterExpression:{exp}"); - return (param, members); - } - static MethodInfo GetEntityValueWithPropertyNameMethod = typeof(EntityUtilExtensions).GetMethod("GetEntityValueWithPropertyName"); - static ConcurrentDictionary> _dicTypeMethod = new ConcurrentDictionary>(); - public ISelect IncludeMany(Expression>> navigateSelector, Action> then = null) where TNavigate : class { - var throwNavigateSelector = new Exception("IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess"); + static (ParameterExpression param, List members) GetExpressionStack(Expression exp) + { + Expression tmpExp = exp; + ParameterExpression param = null; + var members = new List(); + var isbreak = false; + while (isbreak == false) + { + switch (tmpExp.NodeType) + { + case ExpressionType.MemberAccess: + var memExp = tmpExp as MemberExpression; + tmpExp = memExp.Expression; + members.Add(memExp); + continue; + case ExpressionType.Parameter: + param = tmpExp as ParameterExpression; + isbreak = true; + break; + default: + throw new Exception($"表达式错误,它不是连续的 MemberAccess 类型:{exp}"); + } + } + if (param == null) throw new Exception($"表达式错误,它的顶级对象不是 ParameterExpression:{exp}"); + return (param, members); + } + static MethodInfo GetEntityValueWithPropertyNameMethod = typeof(EntityUtilExtensions).GetMethod("GetEntityValueWithPropertyName"); + static ConcurrentDictionary> _dicTypeMethod = new ConcurrentDictionary>(); + public ISelect IncludeMany(Expression>> navigateSelector, Action> then = null) where TNavigate : class + { + var throwNavigateSelector = new Exception("IncludeMany 参数1 类型错误,表达式类型应该为 MemberAccess"); - var expBody = navigateSelector?.Body; - if (expBody == null) return this; - MethodCallExpression whereExp = null; - int takeNumber = 0; - while (expBody.NodeType == ExpressionType.Call) { - throwNavigateSelector = new Exception($"IncludeMany {nameof(navigateSelector)} 参数类型错误,表达式格式应该是 a.collections.Take(1).Where(c => c.aid == a.id)"); - var callExp = (expBody as MethodCallExpression); - switch (callExp.Method.Name) { - case "Where": - whereExp = callExp; - break; - case "Take": takeNumber = int.Parse((callExp.Arguments[1] as ConstantExpression)?.Value?.ToString() ?? "0"); break; - default: throw throwNavigateSelector; - } - expBody = callExp.Object ?? callExp.Arguments.FirstOrDefault(); - } + var expBody = navigateSelector?.Body; + if (expBody == null) return this; + MethodCallExpression whereExp = null; + int takeNumber = 0; + while (expBody.NodeType == ExpressionType.Call) + { + throwNavigateSelector = new Exception($"IncludeMany {nameof(navigateSelector)} 参数类型错误,表达式格式应该是 a.collections.Take(1).Where(c => c.aid == a.id)"); + var callExp = (expBody as MethodCallExpression); + switch (callExp.Method.Name) + { + case "Where": + whereExp = callExp; + break; + case "Take": takeNumber = int.Parse((callExp.Arguments[1] as ConstantExpression)?.Value?.ToString() ?? "0"); break; + default: throw throwNavigateSelector; + } + expBody = callExp.Object ?? callExp.Arguments.FirstOrDefault(); + } - if (expBody.NodeType != ExpressionType.MemberAccess) throw throwNavigateSelector; - var collMem = expBody as MemberExpression; - var (membersParam, members) = GetExpressionStack(collMem.Expression); - var tb = _commonUtils.GetTableByEntity(collMem.Expression.Type); - if (tb == null) throw throwNavigateSelector; - var tbNav = _commonUtils.GetTableByEntity(typeof(TNavigate)); - if (tbNav == null) throw new Exception($"类型 {typeof(TNavigate).FullName} 错误,不能使用 IncludeMany"); + if (expBody.NodeType != ExpressionType.MemberAccess) throw throwNavigateSelector; + var collMem = expBody as MemberExpression; + var (membersParam, members) = GetExpressionStack(collMem.Expression); + var tb = _commonUtils.GetTableByEntity(collMem.Expression.Type); + if (tb == null) throw throwNavigateSelector; + var tbNav = _commonUtils.GetTableByEntity(typeof(TNavigate)); + if (tbNav == null) throw new Exception($"类型 {typeof(TNavigate).FullName} 错误,不能使用 IncludeMany"); - if (collMem.Expression.NodeType != ExpressionType.Parameter) - _commonExpression.ExpressionWhereLambda(_tables, Expression.MakeMemberAccess(collMem.Expression, tb.Properties[tb.ColumnsByCs.First().Value.CsName]), null); + if (collMem.Expression.NodeType != ExpressionType.Parameter) + _commonExpression.ExpressionWhereLambda(_tables, Expression.MakeMemberAccess(collMem.Expression, tb.Properties[tb.ColumnsByCs.First().Value.CsName]), null); - TableRef tbref = null; - var tbrefOneToManyColumns = new List>(); //临时 OneToMany 三个表关联,第三个表需要前两个表确定 - if (whereExp == null) { + TableRef tbref = null; + var tbrefOneToManyColumns = new List>(); //临时 OneToMany 三个表关联,第三个表需要前两个表确定 + if (whereExp == null) + { - tbref = tb.GetTableRef(collMem.Member.Name, true); + tbref = tb.GetTableRef(collMem.Member.Name, true); - } else { - //处理临时关系映射 - tbref = new TableRef { - RefType = TableRefType.OneToMany, - Property = tb.Properties[collMem.Member.Name], - RefEntityType = tbNav.Type - }; - foreach (var whereExpArg in whereExp.Arguments) { - if (whereExpArg.NodeType != ExpressionType.Lambda) continue; - var whereExpArgLamb = whereExpArg as LambdaExpression; + } + else + { + //处理临时关系映射 + tbref = new TableRef + { + RefType = TableRefType.OneToMany, + Property = tb.Properties[collMem.Member.Name], + RefEntityType = tbNav.Type + }; + foreach (var whereExpArg in whereExp.Arguments) + { + if (whereExpArg.NodeType != ExpressionType.Lambda) continue; + var whereExpArgLamb = whereExpArg as LambdaExpression; - Action actWeiParse = null; - actWeiParse = expOrg => { - var binaryExp = expOrg as BinaryExpression; - if (binaryExp == null) throw throwNavigateSelector; + Action actWeiParse = null; + actWeiParse = expOrg => + { + var binaryExp = expOrg as BinaryExpression; + if (binaryExp == null) throw throwNavigateSelector; - switch (binaryExp.NodeType) { - case ExpressionType.AndAlso: - actWeiParse(binaryExp.Left); - actWeiParse(binaryExp.Right); - break; - case ExpressionType.Equal: - var leftP1MemberExp = binaryExp.Left as MemberExpression; - var rightP1MemberExp = binaryExp.Right as MemberExpression; - if (leftP1MemberExp == null || rightP1MemberExp == null) throw throwNavigateSelector; + switch (binaryExp.NodeType) + { + case ExpressionType.AndAlso: + actWeiParse(binaryExp.Left); + actWeiParse(binaryExp.Right); + break; + case ExpressionType.Equal: + var leftP1MemberExp = binaryExp.Left as MemberExpression; + var rightP1MemberExp = binaryExp.Right as MemberExpression; + if (leftP1MemberExp == null || rightP1MemberExp == null) throw throwNavigateSelector; - if (leftP1MemberExp.Expression == whereExpArgLamb.Parameters[0]) { - var (rightMembersParam, rightMembers) = GetExpressionStack(rightP1MemberExp.Expression); - if (rightMembersParam != membersParam) throw throwNavigateSelector; - var isCollMemEquals = rightMembers.Count == members.Count; - if (isCollMemEquals) { - for (var l = 0; l < members.Count; l++) - if (members[l].Member != rightMembers[l].Member) { - isCollMemEquals = false; - break; - } - } - if (isCollMemEquals) { - tbref.Columns.Add(tb.ColumnsByCs[rightP1MemberExp.Member.Name]); - tbrefOneToManyColumns.Add(null); - } else { - var tmpTb = _commonUtils.GetTableByEntity(rightP1MemberExp.Expression.Type); - if (tmpTb == null) throw throwNavigateSelector; - tbref.Columns.Add(tmpTb.ColumnsByCs[rightP1MemberExp.Member.Name]); - tbrefOneToManyColumns.Add(rightMembers); - } - tbref.RefColumns.Add(tbNav.ColumnsByCs[leftP1MemberExp.Member.Name]); - return; - } - if (rightP1MemberExp.Expression == whereExpArgLamb.Parameters[0]) { - var (leftMembersParam, leftMembers) = GetExpressionStack(leftP1MemberExp.Expression); - if (leftMembersParam != membersParam) throw throwNavigateSelector; - var isCollMemEquals = leftMembers.Count == members.Count; - if (isCollMemEquals) { - for (var l = 0; l < members.Count; l++) - if (members[l].Member != leftMembers[l].Member) { - isCollMemEquals = false; - break; - } - } - if (isCollMemEquals) { - tbref.Columns.Add(tb.ColumnsByCs[leftP1MemberExp.Member.Name]); - tbrefOneToManyColumns.Add(null); - } else { - var tmpTb = _commonUtils.GetTableByEntity(leftP1MemberExp.Expression.Type); - if (tmpTb == null) throw throwNavigateSelector; - tbref.Columns.Add(tmpTb.ColumnsByCs[leftP1MemberExp.Member.Name]); - tbrefOneToManyColumns.Add(leftMembers); - } - tbref.RefColumns.Add(tbNav.ColumnsByCs[rightP1MemberExp.Member.Name]); - return; - } + if (leftP1MemberExp.Expression == whereExpArgLamb.Parameters[0]) + { + var (rightMembersParam, rightMembers) = GetExpressionStack(rightP1MemberExp.Expression); + if (rightMembersParam != membersParam) throw throwNavigateSelector; + var isCollMemEquals = rightMembers.Count == members.Count; + if (isCollMemEquals) + { + for (var l = 0; l < members.Count; l++) + if (members[l].Member != rightMembers[l].Member) + { + isCollMemEquals = false; + break; + } + } + if (isCollMemEquals) + { + tbref.Columns.Add(tb.ColumnsByCs[rightP1MemberExp.Member.Name]); + tbrefOneToManyColumns.Add(null); + } + else + { + var tmpTb = _commonUtils.GetTableByEntity(rightP1MemberExp.Expression.Type); + if (tmpTb == null) throw throwNavigateSelector; + tbref.Columns.Add(tmpTb.ColumnsByCs[rightP1MemberExp.Member.Name]); + tbrefOneToManyColumns.Add(rightMembers); + } + tbref.RefColumns.Add(tbNav.ColumnsByCs[leftP1MemberExp.Member.Name]); + return; + } + if (rightP1MemberExp.Expression == whereExpArgLamb.Parameters[0]) + { + var (leftMembersParam, leftMembers) = GetExpressionStack(leftP1MemberExp.Expression); + if (leftMembersParam != membersParam) throw throwNavigateSelector; + var isCollMemEquals = leftMembers.Count == members.Count; + if (isCollMemEquals) + { + for (var l = 0; l < members.Count; l++) + if (members[l].Member != leftMembers[l].Member) + { + isCollMemEquals = false; + break; + } + } + if (isCollMemEquals) + { + tbref.Columns.Add(tb.ColumnsByCs[leftP1MemberExp.Member.Name]); + tbrefOneToManyColumns.Add(null); + } + else + { + var tmpTb = _commonUtils.GetTableByEntity(leftP1MemberExp.Expression.Type); + if (tmpTb == null) throw throwNavigateSelector; + tbref.Columns.Add(tmpTb.ColumnsByCs[leftP1MemberExp.Member.Name]); + tbrefOneToManyColumns.Add(leftMembers); + } + tbref.RefColumns.Add(tbNav.ColumnsByCs[rightP1MemberExp.Member.Name]); + return; + } - throw throwNavigateSelector; - default: throw throwNavigateSelector; - } - }; - actWeiParse(whereExpArgLamb.Body); - break; - } - if (tbref.Columns.Any() == false) throw throwNavigateSelector; - } + throw throwNavigateSelector; + default: throw throwNavigateSelector; + } + }; + actWeiParse(whereExpArgLamb.Body); + break; + } + if (tbref.Columns.Any() == false) throw throwNavigateSelector; + } - _includeToList.Enqueue(listObj => { - var list = listObj as List; - if (list == null) return; - if (list.Any() == false) return; - if (tbref.Columns.Any() == false) return; + _includeToList.Enqueue(listObj => + { + var list = listObj as List; + if (list == null) return; + if (list.Any() == false) return; + if (tbref.Columns.Any() == false) return; - var t1parm = Expression.Parameter(typeof(T1)); - Expression membersExp = t1parm; - foreach (var mem in members) membersExp = Expression.MakeMemberAccess(membersExp, mem.Member); - members.Clear(); + var t1parm = Expression.Parameter(typeof(T1)); + Expression membersExp = t1parm; + foreach (var mem in members) membersExp = Expression.MakeMemberAccess(membersExp, mem.Member); + members.Clear(); - var listValueExp = Expression.Parameter(typeof(List), "listValue"); - var setListValue = Expression.Lambda>>( - Expression.Assign( - Expression.MakeMemberAccess(membersExp, collMem.Member), - Expression.TypeAs(listValueExp, collMem.Type) - ), t1parm, listValueExp).Compile(); + var listValueExp = Expression.Parameter(typeof(List), "listValue"); + var setListValue = Expression.Lambda>>( + Expression.Assign( + Expression.MakeMemberAccess(membersExp, collMem.Member), + Expression.TypeAs(listValueExp, collMem.Type) + ), t1parm, listValueExp).Compile(); - var returnTarget = Expression.Label(typeof(object)); - var propertyNameExp = Expression.Parameter(typeof(string), "propertyName"); - var getListValue1 = Expression.Lambda>( - Expression.Block( - Expression.Return(returnTarget, Expression.Call(null, GetEntityValueWithPropertyNameMethod, Expression.Constant(_orm), Expression.Constant(membersExp.Type), membersExp, propertyNameExp)), - Expression.Label(returnTarget, Expression.Default(typeof(object))) - ), t1parm, propertyNameExp).Compile(); + var returnTarget = Expression.Label(typeof(object)); + var propertyNameExp = Expression.Parameter(typeof(string), "propertyName"); + var getListValue1 = Expression.Lambda>( + Expression.Block( + Expression.Return(returnTarget, Expression.Call(null, GetEntityValueWithPropertyNameMethod, Expression.Constant(_orm), Expression.Constant(membersExp.Type), membersExp, propertyNameExp)), + Expression.Label(returnTarget, Expression.Default(typeof(object))) + ), t1parm, propertyNameExp).Compile(); - var getListValue2 = new List>(); - for (var j = 0; j < tbrefOneToManyColumns.Count; j++) { - if (tbrefOneToManyColumns[j] == null) { - getListValue2.Add(null); - continue; - } - Expression tbrefOneToManyColumnsMembers = t1parm; - foreach (var mem in tbrefOneToManyColumns[j]) tbrefOneToManyColumnsMembers = Expression.MakeMemberAccess(tbrefOneToManyColumnsMembers, mem.Member); - tbrefOneToManyColumns[j].Clear(); - getListValue2.Add(Expression.Lambda>( - Expression.Block( - Expression.Return(returnTarget, Expression.Call(null, GetEntityValueWithPropertyNameMethod, Expression.Constant(_orm), Expression.Constant(tbrefOneToManyColumnsMembers.Type), tbrefOneToManyColumnsMembers, propertyNameExp)), - Expression.Label(returnTarget, Expression.Default(typeof(object))) - ), t1parm, propertyNameExp).Compile()); - } - tbrefOneToManyColumns.Clear(); - Func getListValue = (item, propName, colIndex) => { - if (getListValue2.Any() && getListValue2[colIndex] != null) return getListValue2[colIndex](item, propName); - return getListValue1(item, propName); - }; + var getListValue2 = new List>(); + for (var j = 0; j < tbrefOneToManyColumns.Count; j++) + { + if (tbrefOneToManyColumns[j] == null) + { + getListValue2.Add(null); + continue; + } + Expression tbrefOneToManyColumnsMembers = t1parm; + foreach (var mem in tbrefOneToManyColumns[j]) tbrefOneToManyColumnsMembers = Expression.MakeMemberAccess(tbrefOneToManyColumnsMembers, mem.Member); + tbrefOneToManyColumns[j].Clear(); + getListValue2.Add(Expression.Lambda>( + Expression.Block( + Expression.Return(returnTarget, Expression.Call(null, GetEntityValueWithPropertyNameMethod, Expression.Constant(_orm), Expression.Constant(tbrefOneToManyColumnsMembers.Type), tbrefOneToManyColumnsMembers, propertyNameExp)), + Expression.Label(returnTarget, Expression.Default(typeof(object))) + ), t1parm, propertyNameExp).Compile()); + } + tbrefOneToManyColumns.Clear(); + Func getListValue = (item, propName, colIndex) => + { + if (getListValue2.Any() && getListValue2[colIndex] != null) return getListValue2[colIndex](item, propName); + return getListValue1(item, propName); + }; - foreach (var item in list) - setListValue(item, null); + foreach (var item in list) + setListValue(item, null); - var subSelect = _orm.Select().WithConnection(_connection).WithTransaction(_transaction).TrackToList(_trackToList) as Select1Provider; - if (_tableRules?.Any() == true) - foreach (var tr in _tableRules) subSelect.AsTable(tr); - then?.Invoke(subSelect); - var subSelectT1Alias = subSelect._tables[0].Alias; - var oldWhere = subSelect._where.ToString(); - if (oldWhere.StartsWith(" AND ")) oldWhere = oldWhere.Remove(0, 5); + var subSelect = _orm.Select().WithConnection(_connection).WithTransaction(_transaction).TrackToList(_trackToList) as Select1Provider; + if (_tableRules?.Any() == true) + foreach (var tr in _tableRules) subSelect.AsTable(tr); + then?.Invoke(subSelect); + var subSelectT1Alias = subSelect._tables[0].Alias; + var oldWhere = subSelect._where.ToString(); + if (oldWhere.StartsWith(" AND ")) oldWhere = oldWhere.Remove(0, 5); - switch (tbref.RefType) { - case TableRefType.OneToMany: - if (true) { - var subList = new List(); - var tbref2 = _commonUtils.GetTableByEntity(tbref.RefEntityType); - Func> getWhereDic = () => { - var sbDic = new Dictionary(); - for (var y = 0; y < list.Count; y++) { - var sbWhereOne = new StringBuilder(); - sbWhereOne.Append("("); - for (var z = 0; z < tbref.Columns.Count; z++) { - if (z > 0) sbWhereOne.Append(" AND "); - sbWhereOne.Append(_commonUtils.FormatSql($"{subSelectT1Alias}.{_commonUtils.QuoteSqlName(tbref.RefColumns[z].Attribute.Name)}={{0}}", getListValue(list[y], tbref.Columns[z].CsName, z))); - } - sbWhereOne.Append(")"); - var whereOne = sbWhereOne.ToString(); - sbWhereOne.Clear(); - if (sbDic.ContainsKey(whereOne) == false) sbDic.Add(whereOne, true); - } - return sbDic; - }; - if (takeNumber > 0) { - var af = subSelect.GetAllFieldExpressionTreeLevelAll(); - var sbSql = new StringBuilder(); - var sbDic = getWhereDic(); - foreach (var sbd in sbDic) { - subSelect._where.Clear(); - subSelect.Where(sbd.Key).Where(oldWhere).Limit(takeNumber); - sbSql.Append("\r\nUNION ALL\r\nselect * from (").Append(subSelect.ToSql(af.Field)).Append(") ftb"); - } - sbSql.Remove(0, 13); - if (sbDic.Count == 1) sbSql.Remove(0, 15).Remove(sbSql.Length - 5, 5); - sbDic.Clear(); - subList = subSelect.ToListAfPrivate(sbSql.ToString(), af, null); - sbSql.Clear(); - } else { - subSelect._where.Clear(); - if (tbref.Columns.Count == 1) { - var arrExp = Expression.NewArrayInit(tbref.Columns[0].CsType, - list.Select(a => getListValue(a, tbref.Columns[0].CsName, 0)).Distinct() - .Select(a => Expression.Constant(Convert.ChangeType(a, tbref.Columns[0].CsType))).ToArray()); - var otmExpParm1 = Expression.Parameter(typeof(TNavigate), "a"); - var containsMethod = _dicTypeMethod.GetOrAdd(tbref.Columns[0].CsType, et => new ConcurrentDictionary()).GetOrAdd("Contains", mn => - typeof(Enumerable).GetMethods().Where(a => a.Name == mn).First()).MakeGenericMethod(tbref.Columns[0].CsType); - var refCol = Expression.MakeMemberAccess(otmExpParm1, tbref2.Properties[tbref.RefColumns[0].CsName]); - if (refCol.Type.IsNullableType()) refCol = Expression.Property(refCol, CommonExpression._dicNullableValueProperty.GetOrAdd(refCol.Type, ct1 => ct1.GetProperty("Value"))); - subSelect.Where(Expression.Lambda>( - Expression.Call(null, containsMethod, arrExp, refCol), otmExpParm1)); - } else { - var sbDic = getWhereDic(); - var sbWhere = new StringBuilder(); - foreach (var sbd in sbDic) - sbWhere.Append(" OR ").Append(sbd.Key); - subSelect.Where(sbWhere.Remove(0, 4).ToString()); - sbWhere.Clear(); - sbDic.Clear(); - } - subSelect.Where(oldWhere); - subList = subSelect.ToList(true); - } + switch (tbref.RefType) + { + case TableRefType.OneToMany: + if (true) + { + var subList = new List(); + var tbref2 = _commonUtils.GetTableByEntity(tbref.RefEntityType); + Func> getWhereDic = () => + { + var sbDic = new Dictionary(); + for (var y = 0; y < list.Count; y++) + { + var sbWhereOne = new StringBuilder(); + sbWhereOne.Append("("); + for (var z = 0; z < tbref.Columns.Count; z++) + { + if (z > 0) sbWhereOne.Append(" AND "); + sbWhereOne.Append(_commonUtils.FormatSql($"{subSelectT1Alias}.{_commonUtils.QuoteSqlName(tbref.RefColumns[z].Attribute.Name)}={{0}}", getListValue(list[y], tbref.Columns[z].CsName, z))); + } + sbWhereOne.Append(")"); + var whereOne = sbWhereOne.ToString(); + sbWhereOne.Clear(); + if (sbDic.ContainsKey(whereOne) == false) sbDic.Add(whereOne, true); + } + return sbDic; + }; + if (takeNumber > 0) + { + var af = subSelect.GetAllFieldExpressionTreeLevelAll(); + var sbSql = new StringBuilder(); + var sbDic = getWhereDic(); + foreach (var sbd in sbDic) + { + subSelect._where.Clear(); + subSelect.Where(sbd.Key).Where(oldWhere).Limit(takeNumber); + sbSql.Append("\r\nUNION ALL\r\nselect * from (").Append(subSelect.ToSql(af.Field)).Append(") ftb"); + } + sbSql.Remove(0, 13); + if (sbDic.Count == 1) sbSql.Remove(0, 15).Remove(sbSql.Length - 5, 5); + sbDic.Clear(); + subList = subSelect.ToListAfPrivate(sbSql.ToString(), af, null); + sbSql.Clear(); + } + else + { + subSelect._where.Clear(); + if (tbref.Columns.Count == 1) + { + var arrExp = Expression.NewArrayInit(tbref.Columns[0].CsType, + list.Select(a => getListValue(a, tbref.Columns[0].CsName, 0)).Distinct() + .Select(a => Expression.Constant(Convert.ChangeType(a, tbref.Columns[0].CsType))).ToArray()); + var otmExpParm1 = Expression.Parameter(typeof(TNavigate), "a"); + var containsMethod = _dicTypeMethod.GetOrAdd(tbref.Columns[0].CsType, et => new ConcurrentDictionary()).GetOrAdd("Contains", mn => + typeof(Enumerable).GetMethods().Where(a => a.Name == mn).First()).MakeGenericMethod(tbref.Columns[0].CsType); + var refCol = Expression.MakeMemberAccess(otmExpParm1, tbref2.Properties[tbref.RefColumns[0].CsName]); + if (refCol.Type.IsNullableType()) refCol = Expression.Property(refCol, CommonExpression._dicNullableValueProperty.GetOrAdd(refCol.Type, ct1 => ct1.GetProperty("Value"))); + subSelect.Where(Expression.Lambda>( + Expression.Call(null, containsMethod, arrExp, refCol), otmExpParm1)); + } + else + { + var sbDic = getWhereDic(); + var sbWhere = new StringBuilder(); + foreach (var sbd in sbDic) + sbWhere.Append(" OR ").Append(sbd.Key); + subSelect.Where(sbWhere.Remove(0, 4).ToString()); + sbWhere.Clear(); + sbDic.Clear(); + } + subSelect.Where(oldWhere); + subList = subSelect.ToList(true); + } - if (subList.Any() == false) { - foreach (var item in list) - setListValue(item, new List()); - return; - } + if (subList.Any() == false) + { + foreach (var item in list) + setListValue(item, new List()); + return; + } - Dictionary>> dicList = new Dictionary>>(); - foreach (var item in list) { - if (tbref.Columns.Count == 1) { - dicList.Add(getListValue(item, tbref.Columns[0].CsName, 0).ToString(), Tuple.Create(item, new List())); - } else { - var sb = new StringBuilder(); - for (var z = 0; z < tbref.Columns.Count; z++) { - if (z > 0) sb.Append("*$*"); - sb.Append(getListValue(item, tbref.Columns[z].CsName, z)); - } - dicList.Add(sb.ToString(), Tuple.Create(item, new List())); - sb.Clear(); - } - } - var parentNavs = new List(); - foreach (var navProp in tbref2.Properties) { - if (tbref2.ColumnsByCs.ContainsKey(navProp.Key)) continue; - if (tbref2.ColumnsByCsIgnore.ContainsKey(navProp.Key)) continue; - var tr2ref = tbref2.GetTableRef(navProp.Key, false); - if (tr2ref == null) continue; - if (tr2ref.RefType != TableRefType.ManyToOne) continue; - if (tr2ref.RefEntityType != tb.Type) continue; - parentNavs.Add(navProp.Key); - } - foreach (var nav in subList) { - string key = null; - if (tbref.RefColumns.Count == 1) { - key = _orm.GetEntityValueWithPropertyName(tbref.RefEntityType, nav, tbref.RefColumns[0].CsName).ToString(); - } else { - var sb = new StringBuilder(); - for (var z = 0; z < tbref.RefColumns.Count; z++) { - if (z > 0) sb.Append("*$*"); - sb.Append(_orm.GetEntityValueWithPropertyName(tbref.RefEntityType, nav, tbref.RefColumns[z].CsName)); - } - key = sb.ToString(); - sb.Clear(); - } - if (dicList.TryGetValue(key, out var t1item) == false) return; - t1item.Item2.Add(nav); + Dictionary>> dicList = new Dictionary>>(); + foreach (var item in list) + { + if (tbref.Columns.Count == 1) + { + dicList.Add(getListValue(item, tbref.Columns[0].CsName, 0).ToString(), Tuple.Create(item, new List())); + } + else + { + var sb = new StringBuilder(); + for (var z = 0; z < tbref.Columns.Count; z++) + { + if (z > 0) sb.Append("*$*"); + sb.Append(getListValue(item, tbref.Columns[z].CsName, z)); + } + dicList.Add(sb.ToString(), Tuple.Create(item, new List())); + sb.Clear(); + } + } + var parentNavs = new List(); + foreach (var navProp in tbref2.Properties) + { + if (tbref2.ColumnsByCs.ContainsKey(navProp.Key)) continue; + if (tbref2.ColumnsByCsIgnore.ContainsKey(navProp.Key)) continue; + var tr2ref = tbref2.GetTableRef(navProp.Key, false); + if (tr2ref == null) continue; + if (tr2ref.RefType != TableRefType.ManyToOne) continue; + if (tr2ref.RefEntityType != tb.Type) continue; + parentNavs.Add(navProp.Key); + } + foreach (var nav in subList) + { + string key = null; + if (tbref.RefColumns.Count == 1) + { + key = _orm.GetEntityValueWithPropertyName(tbref.RefEntityType, nav, tbref.RefColumns[0].CsName).ToString(); + } + else + { + var sb = new StringBuilder(); + for (var z = 0; z < tbref.RefColumns.Count; z++) + { + if (z > 0) sb.Append("*$*"); + sb.Append(_orm.GetEntityValueWithPropertyName(tbref.RefEntityType, nav, tbref.RefColumns[z].CsName)); + } + key = sb.ToString(); + sb.Clear(); + } + if (dicList.TryGetValue(key, out var t1item) == false) return; + t1item.Item2.Add(nav); - //将子集合的,多对一,对象设置为当前对象 - foreach (var parentNav in parentNavs) - _orm.SetEntityValueWithPropertyName(tbref.RefMiddleEntityType, nav, parentNav, t1item.Item1); - } - foreach (var t1item in dicList.Values) - setListValue(t1item.Item1, t1item.Item2); - dicList.Clear(); - } - break; - case TableRefType.ManyToMany: - if (true) { - List subList = null; - List midList = new List(); - var tbref2 = _commonUtils.GetTableByEntity(tbref.RefEntityType); - var tbrefMid = _commonUtils.GetTableByEntity(tbref.RefMiddleEntityType); - var sbJoin = new StringBuilder().Append($"{_commonUtils.QuoteSqlName(tbrefMid.DbName)} midtb ON "); - for (var z = 0; z < tbref.RefColumns.Count; z++) { - if (z > 0) sbJoin.Append(" AND "); - sbJoin.Append($"midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[tbref.Columns.Count + z].Attribute.Name)} = a.{_commonUtils.QuoteSqlName(tbref.RefColumns[z].Attribute.Name)}"); - } - subSelect.InnerJoin(sbJoin.ToString()); - sbJoin.Clear(); + //将子集合的,多对一,对象设置为当前对象 + foreach (var parentNav in parentNavs) + _orm.SetEntityValueWithPropertyName(tbref.RefMiddleEntityType, nav, parentNav, t1item.Item1); + } + foreach (var t1item in dicList.Values) + setListValue(t1item.Item1, t1item.Item2); + dicList.Clear(); + } + break; + case TableRefType.ManyToMany: + if (true) + { + List subList = null; + List midList = new List(); + var tbref2 = _commonUtils.GetTableByEntity(tbref.RefEntityType); + var tbrefMid = _commonUtils.GetTableByEntity(tbref.RefMiddleEntityType); + var sbJoin = new StringBuilder().Append($"{_commonUtils.QuoteSqlName(tbrefMid.DbName)} midtb ON "); + for (var z = 0; z < tbref.RefColumns.Count; z++) + { + if (z > 0) sbJoin.Append(" AND "); + sbJoin.Append($"midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[tbref.Columns.Count + z].Attribute.Name)} = a.{_commonUtils.QuoteSqlName(tbref.RefColumns[z].Attribute.Name)}"); + } + subSelect.InnerJoin(sbJoin.ToString()); + sbJoin.Clear(); - var af = subSelect.GetAllFieldExpressionTreeLevelAll(); - (string field, ReadAnonymousTypeInfo read)? otherData = null; - var sbSql = new StringBuilder(); + var af = subSelect.GetAllFieldExpressionTreeLevelAll(); + (string field, ReadAnonymousTypeInfo read)? otherData = null; + var sbSql = new StringBuilder(); - if (_selectExpression == null) {// return this.InternalToList(_selectExpression).Select(a => (a, ()).ToList(); - var field = new StringBuilder(); - var read = new ReadAnonymousTypeInfo(); - read.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; - read.Consturctor = (tbrefMid.TypeLazy ?? tbrefMid.Type).GetConstructor(new Type[0]); - read.Table = tbrefMid; - foreach (var col in tbrefMid.Columns.Values) { - if (tbref.MiddleColumns.Where(a => a.CsName == col.CsName).Any() == false) continue; - var child = new ReadAnonymousTypeInfo { - CsName = col.CsName, - CsType = col.CsType, - DbField = $"midtb.{_commonUtils.QuoteSqlName(col.Attribute.Name)}", - MapType = col.Attribute.MapType, - Property = tbrefMid.Properties[col.CsName] - }; - read.Childs.Add(child); - field.Append(", ").Append(_commonUtils.QuoteReadColumn(child.MapType, child.DbField)); - } - otherData = (field.ToString(), read); - } - Func> getWhereDic = () => { - var sbDic = new Dictionary(); - for (var y = 0; y < list.Count; y++) { - var sbWhereOne = new StringBuilder(); - sbWhereOne.Append("("); - for (var z = 0; z < tbref.Columns.Count; z++) { - if (z > 0) sbWhereOne.Append(" AND "); - sbWhereOne.Append(_commonUtils.FormatSql($" midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[z].Attribute.Name)}={{0}}", getListValue1(list[y], tbref.Columns[z].CsName))); - } - sbWhereOne.Append(")"); - var whereOne = sbWhereOne.ToString(); - sbWhereOne.Clear(); - if (sbDic.ContainsKey(whereOne) == false) sbDic.Add(whereOne, true); - } - return sbDic; - }; + if (_selectExpression == null) + {// return this.InternalToList(_selectExpression).Select(a => (a, ()).ToList(); + var field = new StringBuilder(); + var read = new ReadAnonymousTypeInfo(); + read.ConsturctorType = ReadAnonymousTypeInfoConsturctorType.Properties; + read.Consturctor = (tbrefMid.TypeLazy ?? tbrefMid.Type).GetConstructor(new Type[0]); + read.Table = tbrefMid; + foreach (var col in tbrefMid.Columns.Values) + { + if (tbref.MiddleColumns.Where(a => a.CsName == col.CsName).Any() == false) continue; + var child = new ReadAnonymousTypeInfo + { + CsName = col.CsName, + CsType = col.CsType, + DbField = $"midtb.{_commonUtils.QuoteSqlName(col.Attribute.Name)}", + MapType = col.Attribute.MapType, + Property = tbrefMid.Properties[col.CsName] + }; + read.Childs.Add(child); + field.Append(", ").Append(_commonUtils.QuoteReadColumn(child.MapType, child.DbField)); + } + otherData = (field.ToString(), read); + } + Func> getWhereDic = () => + { + var sbDic = new Dictionary(); + for (var y = 0; y < list.Count; y++) + { + var sbWhereOne = new StringBuilder(); + sbWhereOne.Append("("); + for (var z = 0; z < tbref.Columns.Count; z++) + { + if (z > 0) sbWhereOne.Append(" AND "); + sbWhereOne.Append(_commonUtils.FormatSql($" midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[z].Attribute.Name)}={{0}}", getListValue1(list[y], tbref.Columns[z].CsName))); + } + sbWhereOne.Append(")"); + var whereOne = sbWhereOne.ToString(); + sbWhereOne.Clear(); + if (sbDic.ContainsKey(whereOne) == false) sbDic.Add(whereOne, true); + } + return sbDic; + }; - if (takeNumber > 0) { - var sbDic = getWhereDic(); - foreach (var sbd in sbDic) { - subSelect._where.Clear(); - subSelect.Where(sbd.Key).Where(oldWhere).Limit(takeNumber); - sbSql.Append("\r\nUNION ALL\r\nselect * from (").Append(subSelect.ToSql($"{af.Field}{otherData?.field}")).Append(") ftb"); - } - sbSql.Remove(0, 13); - if (sbDic.Count == 1) sbSql.Remove(0, 15).Remove(sbSql.Length - 5, 5); - sbDic.Clear(); - } else { - subSelect._where.Clear(); - if (tbref.Columns.Count == 1) { - subSelect.Where(_commonUtils.FormatSql($"midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[0].Attribute.Name)} in {{0}}", list.Select(a => getListValue1(a, tbref.Columns[0].CsName)).Distinct())); - } else { - var sbDic = getWhereDic(); - var sbWhere = new StringBuilder(); - foreach (var sbd in sbDic) - sbWhere.Append(" OR ").Append(sbd.Key); - subSelect.Where(sbWhere.Remove(0, 4).ToString()); - sbWhere.Clear(); - sbDic.Clear(); - } - subSelect.Where(oldWhere); - sbSql.Append(subSelect.ToSql($"{af.Field}{otherData?.field}")); - } + if (takeNumber > 0) + { + var sbDic = getWhereDic(); + foreach (var sbd in sbDic) + { + subSelect._where.Clear(); + subSelect.Where(sbd.Key).Where(oldWhere).Limit(takeNumber); + sbSql.Append("\r\nUNION ALL\r\nselect * from (").Append(subSelect.ToSql($"{af.Field}{otherData?.field}")).Append(") ftb"); + } + sbSql.Remove(0, 13); + if (sbDic.Count == 1) sbSql.Remove(0, 15).Remove(sbSql.Length - 5, 5); + sbDic.Clear(); + } + else + { + subSelect._where.Clear(); + if (tbref.Columns.Count == 1) + { + subSelect.Where(_commonUtils.FormatSql($"midtb.{_commonUtils.QuoteSqlName(tbref.MiddleColumns[0].Attribute.Name)} in {{0}}", list.Select(a => getListValue1(a, tbref.Columns[0].CsName)).Distinct())); + } + else + { + var sbDic = getWhereDic(); + var sbWhere = new StringBuilder(); + foreach (var sbd in sbDic) + sbWhere.Append(" OR ").Append(sbd.Key); + subSelect.Where(sbWhere.Remove(0, 4).ToString()); + sbWhere.Clear(); + sbDic.Clear(); + } + subSelect.Where(oldWhere); + sbSql.Append(subSelect.ToSql($"{af.Field}{otherData?.field}")); + } - subList = subSelect.ToListAfPrivate(sbSql.ToString(), af, otherData == null ? null : new[] { (otherData.Value.field, otherData.Value.read, midList) }); - if (subList.Any() == false) { - foreach (var item in list) - setListValue(item, new List()); - return; - } + subList = subSelect.ToListAfPrivate(sbSql.ToString(), af, otherData == null ? null : new[] { (otherData.Value.field, otherData.Value.read, midList) }); + if (subList.Any() == false) + { + foreach (var item in list) + setListValue(item, new List()); + return; + } - Dictionary>>> dicList = new Dictionary>>>(); - foreach (var item in list) { - if (tbref.Columns.Count == 1) { - var dicListKey = getListValue1(item, tbref.Columns[0].CsName).ToString(); - var dicListVal = Tuple.Create(item, new List()); - if (dicList.TryGetValue(dicListKey, out var items) == false) - dicList.Add(dicListKey, items = new List>>()); - items.Add(dicListVal); - } else { - var sb = new StringBuilder(); - for (var z = 0; z < tbref.Columns.Count; z++) { - if (z > 0) sb.Append("*$*"); - sb.Append(getListValue1(item, tbref.Columns[z].CsName)); - } - var dicListKey = sb.ToString(); - var dicListVal = Tuple.Create(item, new List()); - if (dicList.TryGetValue(dicListKey, out var items) == false) - dicList.Add(dicListKey, items = new List>>()); - items.Add(dicListVal); - sb.Clear(); - } - } - for (var a = 0; a < subList.Count; a++) { - string key = null; - if (tbref.Columns.Count == 1) { - key = _orm.GetEntityValueWithPropertyName(tbref.RefMiddleEntityType, midList[a], tbref.MiddleColumns[0].CsName).ToString(); - } else { - var sb = new StringBuilder(); - for (var z = 0; z < tbref.Columns.Count; z++) { - if (z > 0) sb.Append("*$*"); - sb.Append(_orm.GetEntityValueWithPropertyName(tbref.RefMiddleEntityType, midList[a], tbref.MiddleColumns[z].CsName)); - } - key = sb.ToString(); - sb.Clear(); - } - if (dicList.TryGetValue(key, out var t1items) == false) return; - foreach (var t1item in t1items) - t1item.Item2.Add(subList[a]); - } - foreach (var t1items in dicList.Values) - foreach (var t1item in t1items) - setListValue(t1item.Item1, t1item.Item2); - dicList.Clear(); - } - break; - } - }); - return this; - } - } + Dictionary>>> dicList = new Dictionary>>>(); + foreach (var item in list) + { + if (tbref.Columns.Count == 1) + { + var dicListKey = getListValue1(item, tbref.Columns[0].CsName).ToString(); + var dicListVal = Tuple.Create(item, new List()); + if (dicList.TryGetValue(dicListKey, out var items) == false) + dicList.Add(dicListKey, items = new List>>()); + items.Add(dicListVal); + } + else + { + var sb = new StringBuilder(); + for (var z = 0; z < tbref.Columns.Count; z++) + { + if (z > 0) sb.Append("*$*"); + sb.Append(getListValue1(item, tbref.Columns[z].CsName)); + } + var dicListKey = sb.ToString(); + var dicListVal = Tuple.Create(item, new List()); + if (dicList.TryGetValue(dicListKey, out var items) == false) + dicList.Add(dicListKey, items = new List>>()); + items.Add(dicListVal); + sb.Clear(); + } + } + for (var a = 0; a < subList.Count; a++) + { + string key = null; + if (tbref.Columns.Count == 1) + { + key = _orm.GetEntityValueWithPropertyName(tbref.RefMiddleEntityType, midList[a], tbref.MiddleColumns[0].CsName).ToString(); + } + else + { + var sb = new StringBuilder(); + for (var z = 0; z < tbref.Columns.Count; z++) + { + if (z > 0) sb.Append("*$*"); + sb.Append(_orm.GetEntityValueWithPropertyName(tbref.RefMiddleEntityType, midList[a], tbref.MiddleColumns[z].CsName)); + } + key = sb.ToString(); + sb.Clear(); + } + if (dicList.TryGetValue(key, out var t1items) == false) return; + foreach (var t1item in t1items) + t1item.Item2.Add(subList[a]); + } + foreach (var t1items in dicList.Values) + foreach (var t1item in t1items) + setListValue(t1item.Item1, t1item.Item2); + dicList.Clear(); + } + break; + } + }); + return this; + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select2Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select2Provider.cs index bcb5a1fd..d8a756ea 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select2Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select2Provider.cs @@ -5,154 +5,180 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select2Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class { + public abstract class Select2Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + { - public Select2Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - } + public Select2Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy(exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b")); - } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b")); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select3Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select3Provider.cs index 74fcf00a..32f58181 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select3Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select3Provider.cs @@ -5,157 +5,183 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select3Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class - where T3 : class { + public abstract class Select3Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + where T3 : class + { - public Select3Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); - } + public Select3Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy(exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b"), - Expression.Parameter(typeof(T3), "c")); - } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b"), + Expression.Parameter(typeof(T3), "c")); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select4Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select4Provider.cs index e32cf2b0..92260a34 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select4Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select4Provider.cs @@ -5,160 +5,186 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select4Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class - where T3 : class - where T4 : class { + public abstract class Select4Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + where T3 : class + where T4 : class + { - public Select4Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); - } + public Select4Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy(exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b"), - Expression.Parameter(typeof(T3), "c"), - Expression.Parameter(typeof(T4), "d")); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b"), + Expression.Parameter(typeof(T3), "c"), + Expression.Parameter(typeof(T4), "d")); + } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select5Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select5Provider.cs index f7658f27..b59a67c2 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select5Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select5Provider.cs @@ -5,163 +5,189 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select5Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class - where T3 : class - where T4 : class - where T5 : class { + public abstract class Select5Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + where T3 : class + where T4 : class + where T5 : class + { - public Select5Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); - } + public Select5Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy(exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b"), - Expression.Parameter(typeof(T3), "c"), - Expression.Parameter(typeof(T4), "d"), - Expression.Parameter(typeof(T5), "e")); - } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b"), + Expression.Parameter(typeof(T3), "c"), + Expression.Parameter(typeof(T4), "d"), + Expression.Parameter(typeof(T5), "e")); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select6Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select6Provider.cs index 129f85db..10f315ee 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select6Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select6Provider.cs @@ -5,166 +5,192 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select6Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class - where T3 : class - where T4 : class - where T5 : class - where T6 : class { + public abstract class Select6Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + where T3 : class + where T4 : class + where T5 : class + where T6 : class + { - public Select6Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); - } + public Select6Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy(exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b"), - Expression.Parameter(typeof(T3), "c"), - Expression.Parameter(typeof(T4), "d"), - Expression.Parameter(typeof(T5), "e"), - Expression.Parameter(typeof(T6), "f")); - } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b"), + Expression.Parameter(typeof(T3), "c"), + Expression.Parameter(typeof(T4), "d"), + Expression.Parameter(typeof(T5), "e"), + Expression.Parameter(typeof(T6), "f")); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select7Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select7Provider.cs index 12989751..a3b8705a 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select7Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select7Provider.cs @@ -5,169 +5,195 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select7Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class - where T3 : class - where T4 : class - where T5 : class - where T6 : class - where T7 : class { + public abstract class Select7Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + where T3 : class + where T4 : class + where T5 : class + where T6 : class + where T7 : class + { - public Select7Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T7)), Alias = $"SP10g", On = null, Type = SelectTableInfoType.From }); - } + public Select7Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T7)), Alias = $"SP10g", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy(exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b"), - Expression.Parameter(typeof(T3), "c"), - Expression.Parameter(typeof(T4), "d"), - Expression.Parameter(typeof(T5), "e"), - Expression.Parameter(typeof(T6), "f"), - Expression.Parameter(typeof(T7), "g")); - } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b"), + Expression.Parameter(typeof(T3), "c"), + Expression.Parameter(typeof(T4), "d"), + Expression.Parameter(typeof(T5), "e"), + Expression.Parameter(typeof(T6), "f"), + Expression.Parameter(typeof(T7), "g")); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select8Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select8Provider.cs index 3815c2d5..3926173e 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select8Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select8Provider.cs @@ -5,172 +5,198 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select8Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class - where T3 : class - where T4 : class - where T5 : class - where T6 : class - where T7 : class - where T8 : class { + public abstract class Select8Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + where T3 : class + where T4 : class + where T5 : class + where T6 : class + where T7 : class + where T8 : class + { - public Select8Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T7)), Alias = $"SP10g", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T8)), Alias = $"SP10h", On = null, Type = SelectTableInfoType.From }); - } + public Select8Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T7)), Alias = $"SP10g", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T8)), Alias = $"SP10h", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy(exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b"), - Expression.Parameter(typeof(T3), "c"), - Expression.Parameter(typeof(T4), "d"), - Expression.Parameter(typeof(T5), "e"), - Expression.Parameter(typeof(T6), "f"), - Expression.Parameter(typeof(T7), "g"), - Expression.Parameter(typeof(T8), "h")); - } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b"), + Expression.Parameter(typeof(T3), "c"), + Expression.Parameter(typeof(T4), "d"), + Expression.Parameter(typeof(T5), "e"), + Expression.Parameter(typeof(T6), "f"), + Expression.Parameter(typeof(T7), "g"), + Expression.Parameter(typeof(T8), "h")); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/Select9Provider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/Select9Provider.cs index f9223ee3..3c953b74 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/Select9Provider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/Select9Provider.cs @@ -5,175 +5,201 @@ using System.Data; using System.Linq.Expressions; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract class Select9Provider : Select0Provider, T1>, ISelect - where T1 : class - where T2 : class - where T3 : class - where T4 : class - where T5 : class - where T6 : class - where T7 : class - where T8 : class - where T9 : class { + public abstract class Select9Provider : Select0Provider, T1>, ISelect + where T1 : class + where T2 : class + where T3 : class + where T4 : class + where T5 : class + where T6 : class + where T7 : class + where T8 : class + where T9 : class + { - public Select9Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9)); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T7)), Alias = $"SP10g", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T8)), Alias = $"SP10h", On = null, Type = SelectTableInfoType.From }); - _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T9)), Alias = $"SP10i", On = null, Type = SelectTableInfoType.From }); - } + public Select9Provider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) + { + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8), typeof(T9)); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T2)), Alias = $"SP10b", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T3)), Alias = $"SP10c", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T4)), Alias = $"SP10d", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T5)), Alias = $"SP10e", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T6)), Alias = $"SP10f", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T7)), Alias = $"SP10g", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T8)), Alias = $"SP10h", On = null, Type = SelectTableInfoType.From }); + _tables.Add(new SelectTableInfo { Table = _commonUtils.GetTableByEntity(typeof(T9)), Alias = $"SP10i", On = null, Type = SelectTableInfoType.From }); + } - TMember ISelect.Avg(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvg(column?.Body); - } + TMember ISelect.Avg(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvg(column?.Body); + } - Task ISelect.AvgAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalAvgAsync(column?.Body); - } + Task ISelect.AvgAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalAvgAsync(column?.Body); + } - ISelectGrouping ISelect.GroupBy(Expression> exp) { - if (exp == null) return this.InternalGroupBy(exp?.Body); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.InternalGroupBy(exp?.Body); - } + ISelectGrouping ISelect.GroupBy(Expression> exp) + { + if (exp == null) return this.InternalGroupBy(exp?.Body); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.InternalGroupBy(exp?.Body); + } - TMember ISelect.Max(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMax(column?.Body); - } + TMember ISelect.Max(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMax(column?.Body); + } - Task ISelect.MaxAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMaxAsync(column?.Body); - } + Task ISelect.MaxAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMaxAsync(column?.Body); + } - TMember ISelect.Min(Expression> column) { - if (column == null) return default(TMember); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMin(column?.Body); - } + TMember ISelect.Min(Expression> column) + { + if (column == null) return default(TMember); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMin(column?.Body); + } - Task ISelect.MinAsync(Expression> column) { - if (column == null) return Task.FromResult(default(TMember)); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalMinAsync(column?.Body); - } + Task ISelect.MinAsync(Expression> column) + { + if (column == null) return Task.FromResult(default(TMember)); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalMinAsync(column?.Body); + } - ISelect ISelect.OrderBy(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderBy(column?.Body); - } + ISelect ISelect.OrderBy(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderBy(column?.Body); + } - ISelect ISelect.OrderByDescending(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalOrderByDescending(column?.Body); - } + ISelect ISelect.OrderByDescending(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalOrderByDescending(column?.Body); + } - TMember ISelect.Sum(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSum(column?.Body); - } + TMember ISelect.Sum(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSum(column?.Body); + } - Task ISelect.SumAsync(Expression> column) { - if (column == null) this.InternalOrderBy(column?.Body); - for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; - return this.InternalSumAsync(column?.Body); - } + Task ISelect.SumAsync(Expression> column) + { + if (column == null) this.InternalOrderBy(column?.Body); + for (var a = 0; a < column.Parameters.Count; a++) _tables[a].Parameter = column.Parameters[a]; + return this.InternalSumAsync(column?.Body); + } - TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return default(TReturn); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregate(select?.Body); - } + TReturn ISelect.ToAggregate(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return default(TReturn); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregate(select?.Body); + } - Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) { - if (select == null) return Task.FromResult(default(TReturn)); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToAggregateAsync(select?.Body); - } + Task ISelect.ToAggregateAsync(Expression, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, ISelectGroupingAggregate, TReturn>> select) + { + if (select == null) return Task.FromResult(default(TReturn)); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToAggregateAsync(select?.Body); + } - List ISelect.ToList(Expression> select) { - if (select == null) return this.InternalToList(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToList(select?.Body); - } - Task> ISelect.ToListAsync(Expression> select) { - if (select == null) return this.InternalToListAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToListAsync(select?.Body); - } - List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); - Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); - Expression> GetToListDtoSelector() { - var ctor = typeof(TDto).GetConstructor(new Type[0]); - return Expression.Lambda>(Expression.New(ctor), - _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), - Expression.Parameter(typeof(T2), "b"), - Expression.Parameter(typeof(T3), "c"), - Expression.Parameter(typeof(T4), "d"), - Expression.Parameter(typeof(T5), "e"), - Expression.Parameter(typeof(T6), "f"), - Expression.Parameter(typeof(T7), "g"), - Expression.Parameter(typeof(T8), "h"), - Expression.Parameter(typeof(T9), "i")); - } + List ISelect.ToList(Expression> select) + { + if (select == null) return this.InternalToList(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToList(select?.Body); + } + Task> ISelect.ToListAsync(Expression> select) + { + if (select == null) return this.InternalToListAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToListAsync(select?.Body); + } + List ISelect.ToList() => (this as ISelect).ToList(GetToListDtoSelector()); + Task> ISelect.ToListAsync() => (this as ISelect).ToListAsync(GetToListDtoSelector()); + Expression> GetToListDtoSelector() + { + var ctor = typeof(TDto).GetConstructor(new Type[0]); + return Expression.Lambda>(Expression.New(ctor), + _tables[0].Parameter ?? Expression.Parameter(typeof(T1), "a"), + Expression.Parameter(typeof(T2), "b"), + Expression.Parameter(typeof(T3), "c"), + Expression.Parameter(typeof(T4), "d"), + Expression.Parameter(typeof(T5), "e"), + Expression.Parameter(typeof(T6), "f"), + Expression.Parameter(typeof(T7), "g"), + Expression.Parameter(typeof(T8), "h"), + Expression.Parameter(typeof(T9), "i")); + } - DataTable ISelect.ToDataTable(Expression> select) { - if (select == null) return this.InternalToDataTable(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTable(select?.Body); - } + DataTable ISelect.ToDataTable(Expression> select) + { + if (select == null) return this.InternalToDataTable(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTable(select?.Body); + } - Task ISelect.ToDataTableAsync(Expression> select) { - if (select == null) return this.InternalToDataTableAsync(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToDataTableAsync(select?.Body); - } + Task ISelect.ToDataTableAsync(Expression> select) + { + if (select == null) return this.InternalToDataTableAsync(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToDataTableAsync(select?.Body); + } - string ISelect.ToSql(Expression> select) { - if (select == null) return this.InternalToSql(select?.Body); - for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; - return this.InternalToSql(select?.Body); - } + string ISelect.ToSql(Expression> select) + { + if (select == null) return this.InternalToSql(select?.Body); + for (var a = 0; a < select.Parameters.Count; a++) _tables[a].Parameter = select.Parameters[a]; + return this.InternalToSql(select?.Body); + } - ISelect ISelect.Where(Expression> exp) { - if (exp == null) return this.Where(null); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.Where(Expression> exp) + { + if (exp == null) return this.Where(null); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - ISelect ISelect.WhereIf(bool condition, Expression> exp) { - if (condition == false || exp == null) return this; - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); - } + ISelect ISelect.WhereIf(bool condition, Expression> exp) + { + if (condition == false || exp == null) return this; + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)); + } - bool ISelect.Any(Expression> exp) { - if (exp == null) return this.Any(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); - } + bool ISelect.Any(Expression> exp) + { + if (exp == null) return this.Any(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).Any(); + } - Task ISelect.AnyAsync(Expression> exp) { - if (exp == null) return this.AnyAsync(); - for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; - return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); - } - } + Task ISelect.AnyAsync(Expression> exp) + { + if (exp == null) return this.AnyAsync(); + for (var a = 0; a < exp.Parameters.Count; a++) _tables[a].Parameter = exp.Parameters[a]; + return this.Where(_commonExpression.ExpressionWhereLambda(_tables, exp?.Body, null)).AnyAsync(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonProvider/SelectProvider/SelectGroupingProvider.cs b/FreeSql/Internal/CommonProvider/SelectProvider/SelectGroupingProvider.cs index 9389c832..810c9069 100644 --- a/FreeSql/Internal/CommonProvider/SelectProvider/SelectGroupingProvider.cs +++ b/FreeSql/Internal/CommonProvider/SelectProvider/SelectGroupingProvider.cs @@ -7,140 +7,161 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { - public class SelectGroupingProvider : ISelectGrouping { +namespace FreeSql.Internal.CommonProvider +{ + public class SelectGroupingProvider : ISelectGrouping + { - internal object _select; - internal ReadAnonymousTypeInfo _map; - internal CommonExpression _comonExp; - internal List _tables; - public SelectGroupingProvider(object select, ReadAnonymousTypeInfo map, CommonExpression comonExp, List tables) { - _select = select; - _map = map; - _comonExp = comonExp; - _tables = tables; - } + internal object _select; + internal ReadAnonymousTypeInfo _map; + internal CommonExpression _comonExp; + internal List _tables; + public SelectGroupingProvider(object select, ReadAnonymousTypeInfo map, CommonExpression comonExp, List tables) + { + _select = select; + _map = map; + _comonExp = comonExp; + _tables = tables; + } - string getSelectGroupingMapString(Expression[] members) { - if (members.Any() == false) return _map.DbField; - var parentName = ((members.FirstOrDefault() as MemberExpression)?.Expression as MemberExpression)?.Member.Name; - switch (parentName) { - case "Key": - var read = _map; - for (var a = 0; a < members.Length; a++) { - read = read.Childs.Where(z => z.CsName == (members[a] as MemberExpression)?.Member.Name).FirstOrDefault(); - if (read == null) return null; - } - return read.DbField; - case "Value": - var tb = _tables.First(); - var foridx = 0; - if (members.Length > 1) { - var mem0 = (members.FirstOrDefault() as MemberExpression); - var mem0Name = mem0?.Member.Name; - if (mem0Name?.StartsWith("Item") == true && int.TryParse(mem0Name.Substring(4), out var tryitemidx)) { - if (tryitemidx == 1) foridx++; - else { - //var alias = $"SP10{(char)(96 + tryitemidx)}"; - var tmptb = _tables.Where((a,idx) => //a.AliasInit == alias && - a.Table.Type == mem0.Type && idx == tryitemidx - 1).FirstOrDefault(); - if (tmptb != null) { - tb = tmptb; - foridx++; - } - } - } - } - var parmExp = Expression.Parameter(tb.Table.Type, tb.Alias); - Expression retExp = parmExp; - for (var a = foridx; a < members.Length; a++) { - switch (members[a].NodeType) { - case ExpressionType.Call: - retExp = Expression.Call(retExp, (members[a] as MethodCallExpression).Method); - break; - case ExpressionType.MemberAccess: - retExp = Expression.MakeMemberAccess(retExp, (members[a] as MemberExpression).Member); - break; - default: - return null; - } - } - return _comonExp.ExpressionLambdaToSql(retExp, new CommonExpression.ExpTSC { _tables = _tables, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = true, style = CommonExpression.ExpressionStyle.Where }); - } - return null; - } + string getSelectGroupingMapString(Expression[] members) + { + if (members.Any() == false) return _map.DbField; + var parentName = ((members.FirstOrDefault() as MemberExpression)?.Expression as MemberExpression)?.Member.Name; + switch (parentName) + { + case "Key": + var read = _map; + for (var a = 0; a < members.Length; a++) + { + read = read.Childs.Where(z => z.CsName == (members[a] as MemberExpression)?.Member.Name).FirstOrDefault(); + if (read == null) return null; + } + return read.DbField; + case "Value": + var tb = _tables.First(); + var foridx = 0; + if (members.Length > 1) + { + var mem0 = (members.FirstOrDefault() as MemberExpression); + var mem0Name = mem0?.Member.Name; + if (mem0Name?.StartsWith("Item") == true && int.TryParse(mem0Name.Substring(4), out var tryitemidx)) + { + if (tryitemidx == 1) foridx++; + else + { + //var alias = $"SP10{(char)(96 + tryitemidx)}"; + var tmptb = _tables.Where((a, idx) => //a.AliasInit == alias && + a.Table.Type == mem0.Type && idx == tryitemidx - 1).FirstOrDefault(); + if (tmptb != null) + { + tb = tmptb; + foridx++; + } + } + } + } + var parmExp = Expression.Parameter(tb.Table.Type, tb.Alias); + Expression retExp = parmExp; + for (var a = foridx; a < members.Length; a++) + { + switch (members[a].NodeType) + { + case ExpressionType.Call: + retExp = Expression.Call(retExp, (members[a] as MethodCallExpression).Method); + break; + case ExpressionType.MemberAccess: + retExp = Expression.MakeMemberAccess(retExp, (members[a] as MemberExpression).Member); + break; + default: + return null; + } + } + return _comonExp.ExpressionLambdaToSql(retExp, new CommonExpression.ExpTSC { _tables = _tables, tbtype = SelectTableInfoType.From, isQuoteName = true, isDisableDiyParse = true, style = CommonExpression.ExpressionStyle.Where }); + } + return null; + } - public ISelectGrouping Having(Expression, bool>> exp) { - var sql = _comonExp.ExpressionWhereLambda(null, exp, getSelectGroupingMapString); - var method = _select.GetType().GetMethod("Having", new[] { typeof(string), typeof(object) }); - method.Invoke(_select, new object[] { sql, null }); - return this; - } + public ISelectGrouping Having(Expression, bool>> exp) + { + var sql = _comonExp.ExpressionWhereLambda(null, exp, getSelectGroupingMapString); + var method = _select.GetType().GetMethod("Having", new[] { typeof(string), typeof(object) }); + method.Invoke(_select, new object[] { sql, null }); + return this; + } - public ISelectGrouping OrderBy(Expression, TMember>> column) { - var sql = _comonExp.ExpressionWhereLambda(null, column, getSelectGroupingMapString); - var method = _select.GetType().GetMethod("OrderBy", new[] { typeof(string), typeof(object) }); - method.Invoke(_select, new object[] { sql, null }); - return this; - } + public ISelectGrouping OrderBy(Expression, TMember>> column) + { + var sql = _comonExp.ExpressionWhereLambda(null, column, getSelectGroupingMapString); + var method = _select.GetType().GetMethod("OrderBy", new[] { typeof(string), typeof(object) }); + method.Invoke(_select, new object[] { sql, null }); + return this; + } - public ISelectGrouping OrderByDescending(Expression, TMember>> column) { - var sql = _comonExp.ExpressionWhereLambda(null, column, getSelectGroupingMapString); - var method = _select.GetType().GetMethod("OrderBy", new[] { typeof(string), typeof(object) }); - method.Invoke(_select, new object[] { $"{sql} DESC", null }); - return this; - } + public ISelectGrouping OrderByDescending(Expression, TMember>> column) + { + var sql = _comonExp.ExpressionWhereLambda(null, column, getSelectGroupingMapString); + var method = _select.GetType().GetMethod("OrderBy", new[] { typeof(string), typeof(object) }); + method.Invoke(_select, new object[] { $"{sql} DESC", null }); + return this; + } - public List ToList(Expression, TReturn>> select) { - var map = new ReadAnonymousTypeInfo(); - var field = new StringBuilder(); - var index = 0; + public List ToList(Expression, TReturn>> select) + { + var map = new ReadAnonymousTypeInfo(); + var field = new StringBuilder(); + var index = 0; - _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString); - var method = _select.GetType().GetMethod("ToListMapReader", BindingFlags.Instance | BindingFlags.NonPublic); - method = method.MakeGenericMethod(typeof(TReturn)); - return method.Invoke(_select, new object[] { (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null) }) as List; - } - public Task> ToListAsync(Expression, TReturn>> select) { - var map = new ReadAnonymousTypeInfo(); - var field = new StringBuilder(); - var index = 0; + _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString); + var method = _select.GetType().GetMethod("ToListMapReader", BindingFlags.Instance | BindingFlags.NonPublic); + method = method.MakeGenericMethod(typeof(TReturn)); + return method.Invoke(_select, new object[] { (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null) }) as List; + } + public Task> ToListAsync(Expression, TReturn>> select) + { + var map = new ReadAnonymousTypeInfo(); + var field = new StringBuilder(); + var index = 0; - _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString); - var method = _select.GetType().GetMethod("ToListMapReaderAsync", BindingFlags.Instance | BindingFlags.NonPublic); - method = method.MakeGenericMethod(typeof(TReturn)); - return method.Invoke(_select, new object[] { (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null) }) as Task>; - } - public List Select(Expression, TReturn>> select) => ToList(select); + _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString); + var method = _select.GetType().GetMethod("ToListMapReaderAsync", BindingFlags.Instance | BindingFlags.NonPublic); + method = method.MakeGenericMethod(typeof(TReturn)); + return method.Invoke(_select, new object[] { (map, field.Length > 0 ? field.Remove(0, 2).ToString() : null) }) as Task>; + } + public List Select(Expression, TReturn>> select) => ToList(select); - public string ToSql(Expression, TReturn>> select) { - var map = new ReadAnonymousTypeInfo(); - var field = new StringBuilder(); - var index = 0; + public string ToSql(Expression, TReturn>> select) + { + var map = new ReadAnonymousTypeInfo(); + var field = new StringBuilder(); + var index = 0; - _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString); - var method = _select.GetType().GetMethod("ToSql", new[] { typeof(string) }); - return method.Invoke(_select, new object[] { field.Length > 0 ? field.Remove(0, 2).ToString() : null }) as string; - } + _comonExp.ReadAnonymousField(null, field, map, ref index, select, getSelectGroupingMapString); + var method = _select.GetType().GetMethod("ToSql", new[] { typeof(string) }); + return method.Invoke(_select, new object[] { field.Length > 0 ? field.Remove(0, 2).ToString() : null }) as string; + } - public ISelectGrouping Skip(int offset) { - var method = _select.GetType().GetMethod("Skip", new[] { typeof(int) }); - method.Invoke(_select, new object[] { offset }); - return this; - } - public ISelectGrouping Offset(int offset) => this.Skip(offset); + public ISelectGrouping Skip(int offset) + { + var method = _select.GetType().GetMethod("Skip", new[] { typeof(int) }); + method.Invoke(_select, new object[] { offset }); + return this; + } + public ISelectGrouping Offset(int offset) => this.Skip(offset); - public ISelectGrouping Limit(int limit) { - var method = _select.GetType().GetMethod("Limit", new[] { typeof(int) }); - method.Invoke(_select, new object[] { limit }); - return this; - } - public ISelectGrouping Take(int limit) => this.Limit(limit); + public ISelectGrouping Limit(int limit) + { + var method = _select.GetType().GetMethod("Limit", new[] { typeof(int) }); + method.Invoke(_select, new object[] { limit }); + return this; + } + public ISelectGrouping Take(int limit) => this.Limit(limit); - public ISelectGrouping Page(int pageNumber, int pageSize) { - var method = _select.GetType().GetMethod("Page", new[] { typeof(int), typeof(int) }); - method.Invoke(_select, new object[] { pageNumber, pageSize }); - return this; - } - } + public ISelectGrouping Page(int pageNumber, int pageSize) + { + var method = _select.GetType().GetMethod("Page", new[] { typeof(int), typeof(int) }); + method.Invoke(_select, new object[] { pageNumber, pageSize }); + return this; + } + } } diff --git a/FreeSql/Internal/CommonProvider/UpdateProvider.cs b/FreeSql/Internal/CommonProvider/UpdateProvider.cs index 9843e35b..1c06ebcb 100644 --- a/FreeSql/Internal/CommonProvider/UpdateProvider.cs +++ b/FreeSql/Internal/CommonProvider/UpdateProvider.cs @@ -10,552 +10,668 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Internal.CommonProvider { +namespace FreeSql.Internal.CommonProvider +{ - public abstract partial class UpdateProvider : IUpdate where T1 : class { - protected IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - protected List _source = new List(); - protected Dictionary _ignore = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - protected TableInfo _table; - protected Func _tableRule; - protected StringBuilder _where = new StringBuilder(); - protected StringBuilder _set = new StringBuilder(); - protected StringBuilder _setIncr = new StringBuilder(); - protected List _params = new List(); - protected List _paramsSource = new List(); - protected bool _noneParameter; - protected DbTransaction _transaction; - protected DbConnection _connection; + public abstract partial class UpdateProvider : IUpdate where T1 : class + { + protected IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + protected List _source = new List(); + protected Dictionary _ignore = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + protected TableInfo _table; + protected Func _tableRule; + protected StringBuilder _where = new StringBuilder(); + protected StringBuilder _set = new StringBuilder(); + protected StringBuilder _setIncr = new StringBuilder(); + protected List _params = new List(); + protected List _paramsSource = new List(); + protected bool _noneParameter; + protected DbTransaction _transaction; + protected DbConnection _connection; - public UpdateProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - _table = _commonUtils.GetTableByEntity(typeof(T1)); - _noneParameter = _orm.CodeFirst.IsNoneCommandParameter; - this.Where(_commonUtils.WhereObject(_table, "", dywhere)); - if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); - } + public UpdateProvider(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + _table = _commonUtils.GetTableByEntity(typeof(T1)); + _noneParameter = _orm.CodeFirst.IsNoneCommandParameter; + this.Where(_commonUtils.WhereObject(_table, "", dywhere)); + if (_orm.CodeFirst.IsAutoSyncStructure && typeof(T1) != typeof(object)) _orm.CodeFirst.SyncStructure(); + } - protected void ClearData() { - _source.Clear(); - _ignore.Clear(); - _where.Clear(); - _set.Clear(); - _setIncr.Clear(); - _params.Clear(); - _paramsSource.Clear(); - } + protected void ClearData() + { + _source.Clear(); + _ignore.Clear(); + _where.Clear(); + _set.Clear(); + _setIncr.Clear(); + _params.Clear(); + _paramsSource.Clear(); + } - public IUpdate WithTransaction(DbTransaction transaction) { - _transaction = transaction; - _connection = _transaction?.Connection; - return this; - } - public IUpdate WithConnection(DbConnection connection) { - if (_transaction?.Connection != connection) _transaction = null; - _connection = connection; - return this; - } + public IUpdate WithTransaction(DbTransaction transaction) + { + _transaction = transaction; + _connection = _transaction?.Connection; + return this; + } + public IUpdate WithConnection(DbConnection connection) + { + if (_transaction?.Connection != connection) _transaction = null; + _connection = connection; + return this; + } - public IUpdate NoneParameter() { - _noneParameter = true; - return this; - } + public IUpdate NoneParameter() + { + _noneParameter = true; + return this; + } - protected void ValidateVersionAndThrow(int affrows) { - if (_table.VersionColumn != null && _source.Count > 0) { - if (affrows != _source.Count) - throw new Exception($"记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{_source.Count},影响的行数{affrows}。"); - foreach (var d in _source) - _orm.SetEntityIncrByWithPropertyName(_table.Type, d, _table.VersionColumn.CsName, 1); - } - } + protected void ValidateVersionAndThrow(int affrows) + { + if (_table.VersionColumn != null && _source.Count > 0) + { + if (affrows != _source.Count) + throw new Exception($"记录可能不存在,或者【行级乐观锁】版本过旧,更新数量{_source.Count},影响的行数{affrows}。"); + foreach (var d in _source) + _orm.SetEntityIncrByWithPropertyName(_table.Type, d, _table.VersionColumn.CsName, 1); + } + } - #region 参数化数据限制,或values数量限制 - internal List[] SplitSource(int valuesLimit, int parameterLimit) { - valuesLimit = valuesLimit - 1; - parameterLimit = parameterLimit - 1; - if (_source == null || _source.Any() == false) return new List[0]; - if (_source.Count == 1) return new[] { _source }; - if (_noneParameter) { - if (_source.Count < valuesLimit) return new[] { _source }; + #region 参数化数据限制,或values数量限制 + internal List[] SplitSource(int valuesLimit, int parameterLimit) + { + valuesLimit = valuesLimit - 1; + parameterLimit = parameterLimit - 1; + if (_source == null || _source.Any() == false) return new List[0]; + if (_source.Count == 1) return new[] { _source }; + if (_noneParameter) + { + if (_source.Count < valuesLimit) return new[] { _source }; - var execCount = (int)Math.Ceiling(1.0 * _source.Count / valuesLimit); - var ret = new List[execCount]; - for (var a = 0; a < execCount; a++) { - var subSource = new List(); - subSource = _source.GetRange(a * valuesLimit, Math.Min(valuesLimit, _source.Count - a * valuesLimit)); - ret[a] = subSource; - } - return ret; - } else { - var colSum = _table.Columns.Count - _ignore.Count; - var takeMax = parameterLimit / colSum; - var pamTotal = colSum * _source.Count; - if (pamTotal < parameterLimit) return new[] { _source }; + var execCount = (int)Math.Ceiling(1.0 * _source.Count / valuesLimit); + var ret = new List[execCount]; + for (var a = 0; a < execCount; a++) + { + var subSource = new List(); + subSource = _source.GetRange(a * valuesLimit, Math.Min(valuesLimit, _source.Count - a * valuesLimit)); + ret[a] = subSource; + } + return ret; + } + else + { + var colSum = _table.Columns.Count - _ignore.Count; + var takeMax = parameterLimit / colSum; + var pamTotal = colSum * _source.Count; + if (pamTotal < parameterLimit) return new[] { _source }; - var execCount = (int)Math.Ceiling(1.0 * pamTotal / takeMax / colSum); - var ret = new List[execCount]; - for (var a = 0; a < execCount; a++) { - var subSource = new List(); - subSource = _source.GetRange(a * takeMax, Math.Min(takeMax, _source.Count - a * takeMax)); - ret[a] = subSource; - } - return ret; - } - } - protected int SplitExecuteAffrows(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - var ret = 0; - if (ss.Length <= 1) { - ret = this.RawExecuteAffrows(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret += this.RawExecuteAffrows(); - } - } else { - using (var conn = _orm.Ado.MasterPool.Get()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret += this.RawExecuteAffrows(); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - async protected Task SplitExecuteAffrowsAsync(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - var ret = 0; - if (ss.Length <= 1) { - ret = await this.RawExecuteAffrowsAsync(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret += await this.RawExecuteAffrowsAsync(); - } - } else { - using (var conn = await _orm.Ado.MasterPool.GetAsync()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret += await this.RawExecuteAffrowsAsync(); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - protected List SplitExecuteUpdated(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - var ret = new List(); - if (ss.Length <= 1) { - ret = this.RawExecuteUpdated(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret.AddRange(this.RawExecuteUpdated()); - } - } else { - using (var conn = _orm.Ado.MasterPool.Get()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret.AddRange(this.RawExecuteUpdated()); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - async protected Task> SplitExecuteUpdatedAsync(int valuesLimit, int parameterLimit) { - var ss = SplitSource(valuesLimit, parameterLimit); - var ret = new List(); - if (ss.Length <= 1) { - ret = await this.RawExecuteUpdatedAsync(); - ClearData(); - return ret; - } - if (_transaction != null) { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret.AddRange(await this.RawExecuteUpdatedAsync()); - } - } else { - using (var conn = await _orm.Ado.MasterPool.GetAsync()) { - _transaction = conn.Value.BeginTransaction(); - try { - for (var a = 0; a < ss.Length; a++) { - _source = ss[a]; - ret.AddRange(await this.RawExecuteUpdatedAsync()); - } - _transaction.Commit(); - } catch { - _transaction.Rollback(); - throw; - } - _transaction = null; - } - } - ClearData(); - return ret; - } - #endregion + var execCount = (int)Math.Ceiling(1.0 * pamTotal / takeMax / colSum); + var ret = new List[execCount]; + for (var a = 0; a < execCount; a++) + { + var subSource = new List(); + subSource = _source.GetRange(a * takeMax, Math.Min(takeMax, _source.Count - a * takeMax)); + ret[a] = subSource; + } + return ret; + } + } + protected int SplitExecuteAffrows(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + var ret = 0; + if (ss.Length <= 1) + { + ret = this.RawExecuteAffrows(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret += this.RawExecuteAffrows(); + } + } + else + { + using (var conn = _orm.Ado.MasterPool.Get()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret += this.RawExecuteAffrows(); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + async protected Task SplitExecuteAffrowsAsync(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + var ret = 0; + if (ss.Length <= 1) + { + ret = await this.RawExecuteAffrowsAsync(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret += await this.RawExecuteAffrowsAsync(); + } + } + else + { + using (var conn = await _orm.Ado.MasterPool.GetAsync()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret += await this.RawExecuteAffrowsAsync(); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + protected List SplitExecuteUpdated(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + var ret = new List(); + if (ss.Length <= 1) + { + ret = this.RawExecuteUpdated(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret.AddRange(this.RawExecuteUpdated()); + } + } + else + { + using (var conn = _orm.Ado.MasterPool.Get()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret.AddRange(this.RawExecuteUpdated()); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + async protected Task> SplitExecuteUpdatedAsync(int valuesLimit, int parameterLimit) + { + var ss = SplitSource(valuesLimit, parameterLimit); + var ret = new List(); + if (ss.Length <= 1) + { + ret = await this.RawExecuteUpdatedAsync(); + ClearData(); + return ret; + } + if (_transaction != null) + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret.AddRange(await this.RawExecuteUpdatedAsync()); + } + } + else + { + using (var conn = await _orm.Ado.MasterPool.GetAsync()) + { + _transaction = conn.Value.BeginTransaction(); + try + { + for (var a = 0; a < ss.Length; a++) + { + _source = ss[a]; + ret.AddRange(await this.RawExecuteUpdatedAsync()); + } + _transaction.Commit(); + } + catch + { + _transaction.Rollback(); + throw; + } + _transaction = null; + } + } + ClearData(); + return ret; + } + #endregion - protected int RawExecuteAffrows() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; - var dbParms = _params.Concat(_paramsSource).ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var affrows = 0; - Exception exception = null; - try { - affrows = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, dbParms); - ValidateVersionAndThrow(affrows); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, affrows); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return affrows; - } - async protected Task RawExecuteAffrowsAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; - var dbParms = _params.Concat(_paramsSource).ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var affrows = 0; - Exception exception = null; - try { - affrows = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - ValidateVersionAndThrow(affrows); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, affrows); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return affrows; - } - protected abstract List RawExecuteUpdated(); - protected abstract Task> RawExecuteUpdatedAsync(); + protected int RawExecuteAffrows() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; + var dbParms = _params.Concat(_paramsSource).ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var affrows = 0; + Exception exception = null; + try + { + affrows = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, dbParms); + ValidateVersionAndThrow(affrows); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, affrows); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return affrows; + } + async protected Task RawExecuteAffrowsAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; + var dbParms = _params.Concat(_paramsSource).ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var affrows = 0; + Exception exception = null; + try + { + affrows = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + ValidateVersionAndThrow(affrows); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, affrows); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return affrows; + } + protected abstract List RawExecuteUpdated(); + protected abstract Task> RawExecuteUpdatedAsync(); - public abstract int ExecuteAffrows(); - public abstract Task ExecuteAffrowsAsync(); - public abstract List ExecuteUpdated(); - public abstract Task> ExecuteUpdatedAsync(); + public abstract int ExecuteAffrows(); + public abstract Task ExecuteAffrowsAsync(); + public abstract List ExecuteUpdated(); + public abstract Task> ExecuteUpdatedAsync(); - public IUpdate IgnoreColumns(Expression> columns) { - var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, columns?.Body, false, null).Distinct(); - _ignore.Clear(); - foreach (var col in cols) _ignore.Add(col, true); - return this; - } - public IUpdate UpdateColumns(Expression> columns) { - var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, columns?.Body, false, null).ToDictionary(a => a, a => true); - _ignore.Clear(); - foreach (var col in _table.Columns.Values) - if (cols.ContainsKey(col.Attribute.Name) == false) - _ignore.Add(col.Attribute.Name, true); - return this; - } + public IUpdate IgnoreColumns(Expression> columns) + { + var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, columns?.Body, false, null).Distinct(); + _ignore.Clear(); + foreach (var col in cols) _ignore.Add(col, true); + return this; + } + public IUpdate UpdateColumns(Expression> columns) + { + var cols = _commonExpression.ExpressionSelectColumns_MemberAccess_New_NewArrayInit(null, columns?.Body, false, null).ToDictionary(a => a, a => true); + _ignore.Clear(); + foreach (var col in _table.Columns.Values) + if (cols.ContainsKey(col.Attribute.Name) == false) + _ignore.Add(col.Attribute.Name, true); + return this; + } - public IUpdate IgnoreColumns(string[] columns) { - _ignore.Clear(); - foreach (var col in columns) _ignore.Add(col, true); - return this; - } - public IUpdate UpdateColumns(string[] columns) { - var cols = columns.ToDictionary(a => a); - _ignore.Clear(); - foreach (var col in _table.Columns.Values) - if (cols.ContainsKey(col.Attribute.Name) == false) - _ignore.Add(col.Attribute.Name, true); - return this; - } + public IUpdate IgnoreColumns(string[] columns) + { + _ignore.Clear(); + foreach (var col in columns) _ignore.Add(col, true); + return this; + } + public IUpdate UpdateColumns(string[] columns) + { + var cols = columns.ToDictionary(a => a); + _ignore.Clear(); + foreach (var col in _table.Columns.Values) + if (cols.ContainsKey(col.Attribute.Name) == false) + _ignore.Add(col.Attribute.Name, true); + return this; + } - public IUpdate SetSource(T1 source) => this.SetSource(new[] { source }); - public IUpdate SetSource(IEnumerable source) { - if (source == null || source.Any() == false) return this; - _source.AddRange(source.Where(a => a != null)); - return this; - } + public IUpdate SetSource(T1 source) => this.SetSource(new[] { source }); + public IUpdate SetSource(IEnumerable source) + { + if (source == null || source.Any() == false) return this; + _source.AddRange(source.Where(a => a != null)); + return this; + } - public IUpdate Set(Expression> column, TMember value) { - var cols = new List(); - _commonExpression.ExpressionSelectColumn_MemberAccess(null, cols, SelectTableInfoType.From, column?.Body, true, null); - if (cols.Count != 1) return this; - var col = cols.First(); - object paramVal = null; - if (col.Column.Attribute.MapType == typeof(TMember)) paramVal = value; - else paramVal = Utils.GetDataReaderValue(col.Column.Attribute.MapType, value); - _set.Append(", ").Append(_commonUtils.QuoteSqlName(col.Column.Attribute.Name)).Append(" = "); - if (_noneParameter) { - _set.Append(_commonUtils.GetNoneParamaterSqlValue(_params, col.Column.Attribute.MapType, paramVal)); - } else { - _set.Append(_commonUtils.QuoteWriteParamter(col.Column.Attribute.MapType, $"{_commonUtils.QuoteParamterName("p_")}{_params.Count}")); - _commonUtils.AppendParamter(_params, null, col.Column.Attribute.MapType, paramVal); - } - //foreach (var t in _source) Utils.FillPropertyValue(t, tryf.CsName, value); - return this; - } - public IUpdate Set(Expression> exp) { - var body = exp?.Body; - var nodeType = body?.NodeType; - if (nodeType == ExpressionType.Equal) { - _set.Append(", ").Append(_commonExpression.ExpressionWhereLambdaNoneForeignObject(null, _table, null, exp, null)); - return this; - } - - if (nodeType == ExpressionType.MemberInit) { - var initExp = body as MemberInitExpression; - if (initExp.Bindings?.Count > 0) { - for (var a = 0; a < initExp.Bindings.Count; a++) { - var initAssignExp = (initExp.Bindings[a] as MemberAssignment); - if (initAssignExp == null) continue; - var memberName = initExp.Bindings[a].Member.Name; - if (_table.ColumnsByCsIgnore.ContainsKey(memberName)) continue; - if (_table.ColumnsByCs.TryGetValue(memberName, out var col) == false) throw new Exception($"找不到属性:{memberName}"); - var memberValue = _commonExpression.ExpressionLambdaToSql(initAssignExp.Expression, new CommonExpression.ExpTSC { }); - _setIncr.Append(", ").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = ").Append(memberValue); - } - } - return this; - } - if (body is BinaryExpression == false && - nodeType != ExpressionType.Call) return this; - var cols = new List(); - var expt = _commonExpression.ExpressionWhereLambdaNoneForeignObject(null, _table, cols, exp, null); - if (cols.Any() == false) return this; - foreach (var col in cols) { - if (col.Column.Attribute.IsNullable == true && col.Column.Attribute.MapType.IsNullableType()) { - var replval = _orm.CodeFirst.GetDbInfo(col.Column.Attribute.MapType.GenericTypeArguments.FirstOrDefault())?.defaultValue; - if (replval == null) continue; - var replname = _commonUtils.QuoteSqlName(col.Column.Attribute.Name); - expt = expt.Replace(replname, _commonUtils.IsNull(replname, _commonUtils.FormatSql("{0}", replval))); - } - } - _setIncr.Append(", ").Append(_commonUtils.QuoteSqlName(cols.First().Column.Attribute.Name)).Append(" = ").Append(expt); - return this; - } - public IUpdate SetRaw(string sql, object parms = null) { - if (string.IsNullOrEmpty(sql)) return this; - _set.Append(", ").Append(sql); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this; - } + public IUpdate Set(Expression> column, TMember value) + { + var cols = new List(); + _commonExpression.ExpressionSelectColumn_MemberAccess(null, cols, SelectTableInfoType.From, column?.Body, true, null); + if (cols.Count != 1) return this; + var col = cols.First(); + object paramVal = null; + if (col.Column.Attribute.MapType == typeof(TMember)) paramVal = value; + else paramVal = Utils.GetDataReaderValue(col.Column.Attribute.MapType, value); + _set.Append(", ").Append(_commonUtils.QuoteSqlName(col.Column.Attribute.Name)).Append(" = "); + if (_noneParameter) + { + _set.Append(_commonUtils.GetNoneParamaterSqlValue(_params, col.Column.Attribute.MapType, paramVal)); + } + else + { + _set.Append(_commonUtils.QuoteWriteParamter(col.Column.Attribute.MapType, $"{_commonUtils.QuoteParamterName("p_")}{_params.Count}")); + _commonUtils.AppendParamter(_params, null, col.Column.Attribute.MapType, paramVal); + } + //foreach (var t in _source) Utils.FillPropertyValue(t, tryf.CsName, value); + return this; + } + public IUpdate Set(Expression> exp) + { + var body = exp?.Body; + var nodeType = body?.NodeType; + if (nodeType == ExpressionType.Equal) + { + _set.Append(", ").Append(_commonExpression.ExpressionWhereLambdaNoneForeignObject(null, _table, null, exp, null)); + return this; + } - public IUpdate Where(Expression> expression) => this.Where(_commonExpression.ExpressionWhereLambdaNoneForeignObject(null, _table, null, expression?.Body, null)); - public IUpdate Where(string sql, object parms = null) { - if (string.IsNullOrEmpty(sql)) return this; - var args = new Aop.WhereEventArgs(sql, parms); - _orm.Aop.Where?.Invoke(this, new Aop.WhereEventArgs(sql, parms)); - if (args.IsCancel == true) return this; + if (nodeType == ExpressionType.MemberInit) + { + var initExp = body as MemberInitExpression; + if (initExp.Bindings?.Count > 0) + { + for (var a = 0; a < initExp.Bindings.Count; a++) + { + var initAssignExp = (initExp.Bindings[a] as MemberAssignment); + if (initAssignExp == null) continue; + var memberName = initExp.Bindings[a].Member.Name; + if (_table.ColumnsByCsIgnore.ContainsKey(memberName)) continue; + if (_table.ColumnsByCs.TryGetValue(memberName, out var col) == false) throw new Exception($"找不到属性:{memberName}"); + var memberValue = _commonExpression.ExpressionLambdaToSql(initAssignExp.Expression, new CommonExpression.ExpTSC { }); + _setIncr.Append(", ").Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = ").Append(memberValue); + } + } + return this; + } + if (body is BinaryExpression == false && + nodeType != ExpressionType.Call) return this; + var cols = new List(); + var expt = _commonExpression.ExpressionWhereLambdaNoneForeignObject(null, _table, cols, exp, null); + if (cols.Any() == false) return this; + foreach (var col in cols) + { + if (col.Column.Attribute.IsNullable == true && col.Column.Attribute.MapType.IsNullableType()) + { + var replval = _orm.CodeFirst.GetDbInfo(col.Column.Attribute.MapType.GenericTypeArguments.FirstOrDefault())?.defaultValue; + if (replval == null) continue; + var replname = _commonUtils.QuoteSqlName(col.Column.Attribute.Name); + expt = expt.Replace(replname, _commonUtils.IsNull(replname, _commonUtils.FormatSql("{0}", replval))); + } + } + _setIncr.Append(", ").Append(_commonUtils.QuoteSqlName(cols.First().Column.Attribute.Name)).Append(" = ").Append(expt); + return this; + } + public IUpdate SetRaw(string sql, object parms = null) + { + if (string.IsNullOrEmpty(sql)) return this; + _set.Append(", ").Append(sql); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this; + } - _where.Append(" AND (").Append(sql).Append(")"); - if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); - return this; - } - public IUpdate Where(T1 item) => this.Where(new[] { item }); - public IUpdate Where(IEnumerable items) => this.Where(_commonUtils.WhereItems(_table, "", items)); - public IUpdate WhereExists(ISelect select, bool notExists = false) where TEntity2 : class => this.Where($"{(notExists ? "NOT " : "")}EXISTS({select.ToSql("1")})"); - public IUpdate WhereDynamic(object dywhere) => this.Where(_commonUtils.WhereObject(_table, "", dywhere)); + public IUpdate Where(Expression> expression) => this.Where(_commonExpression.ExpressionWhereLambdaNoneForeignObject(null, _table, null, expression?.Body, null)); + public IUpdate Where(string sql, object parms = null) + { + if (string.IsNullOrEmpty(sql)) return this; + var args = new Aop.WhereEventArgs(sql, parms); + _orm.Aop.Where?.Invoke(this, new Aop.WhereEventArgs(sql, parms)); + if (args.IsCancel == true) return this; - protected string WhereCaseSource(string CsName, Func thenValue) { - if (_source.Any() == false) return null; - if (_table.ColumnsByCs.ContainsKey(CsName) == false) throw new Exception($"找不到 {CsName} 对应的列"); - if (thenValue == null) throw new ArgumentNullException("thenValue 参数不可为 null"); + _where.Append(" AND (").Append(sql).Append(")"); + if (parms != null) _params.AddRange(_commonUtils.GetDbParamtersByObject(sql, parms)); + return this; + } + public IUpdate Where(T1 item) => this.Where(new[] { item }); + public IUpdate Where(IEnumerable items) => this.Where(_commonUtils.WhereItems(_table, "", items)); + public IUpdate WhereExists(ISelect select, bool notExists = false) where TEntity2 : class => this.Where($"{(notExists ? "NOT " : "")}EXISTS({select.ToSql("1")})"); + public IUpdate WhereDynamic(object dywhere) => this.Where(_commonUtils.WhereObject(_table, "", dywhere)); - if (_source.Count == 0) return null; - if (_source.Count == 1) { + protected string WhereCaseSource(string CsName, Func thenValue) + { + if (_source.Any() == false) return null; + if (_table.ColumnsByCs.ContainsKey(CsName) == false) throw new Exception($"找不到 {CsName} 对应的列"); + if (thenValue == null) throw new ArgumentNullException("thenValue 参数不可为 null"); - var col = _table.ColumnsByCs[CsName]; - var sb = new StringBuilder(); + if (_source.Count == 0) return null; + if (_source.Count == 1) + { - sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = "); - sb.Append(thenValue(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, col.Attribute.MapType, col.GetMapValue(_source.First())))); + var col = _table.ColumnsByCs[CsName]; + var sb = new StringBuilder(); - return sb.ToString(); + sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = "); + sb.Append(thenValue(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, col.Attribute.MapType, col.GetMapValue(_source.First())))); - } else { - var caseWhen = new StringBuilder(); - caseWhen.Append("CASE "); - ToSqlCase(caseWhen, _table.Primarys); - var cw = caseWhen.ToString(); + return sb.ToString(); - var col = _table.ColumnsByCs[CsName]; - var sb = new StringBuilder(); - sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = "); + } + else + { + var caseWhen = new StringBuilder(); + caseWhen.Append("CASE "); + ToSqlCase(caseWhen, _table.Primarys); + var cw = caseWhen.ToString(); - var isnull = false; - var cwsb = new StringBuilder().Append(cw); - foreach (var d in _source) { - cwsb.Append(" \r\nWHEN "); - ToSqlWhen(cwsb, _table.Primarys, d); - cwsb.Append(" THEN "); - var value = col.GetMapValue(d); - cwsb.Append(thenValue(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, col.Attribute.MapType, value))); - if (isnull == false) isnull = value == null || value == DBNull.Value; - } - cwsb.Append(" END"); - if (isnull == false) sb.Append(cwsb.ToString()); - else sb.Append("NULL"); - cwsb.Clear(); + var col = _table.ColumnsByCs[CsName]; + var sb = new StringBuilder(); + sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = "); - return sb.ToString(); - } - } + var isnull = false; + var cwsb = new StringBuilder().Append(cw); + foreach (var d in _source) + { + cwsb.Append(" \r\nWHEN "); + ToSqlWhen(cwsb, _table.Primarys, d); + cwsb.Append(" THEN "); + var value = col.GetMapValue(d); + cwsb.Append(thenValue(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, col.Attribute.MapType, value))); + if (isnull == false) isnull = value == null || value == DBNull.Value; + } + cwsb.Append(" END"); + if (isnull == false) sb.Append(cwsb.ToString()); + else sb.Append("NULL"); + cwsb.Clear(); - protected abstract void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys); - protected abstract void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d); + return sb.ToString(); + } + } - public IUpdate AsTable(Func tableRule) { - _tableRule = tableRule; - return this; - } - public IUpdate AsType(Type entityType) { - if (entityType == typeof(object)) throw new Exception("IUpdate.AsType 参数不支持指定为 object"); - if (entityType == _table.Type) return this; - var newtb = _commonUtils.GetTableByEntity(entityType); - _table = newtb ?? throw new Exception("IUpdate.AsType 参数错误,请传入正确的实体类型"); - if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); - return this; - } + protected abstract void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys); + protected abstract void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d); - public string ToSql() { - if (_where.Length == 0 && _source.Any() == false) return null; + public IUpdate AsTable(Func tableRule) + { + _tableRule = tableRule; + return this; + } + public IUpdate AsType(Type entityType) + { + if (entityType == typeof(object)) throw new Exception("IUpdate.AsType 参数不支持指定为 object"); + if (entityType == _table.Type) return this; + var newtb = _commonUtils.GetTableByEntity(entityType); + _table = newtb ?? throw new Exception("IUpdate.AsType 参数错误,请传入正确的实体类型"); + if (_orm.CodeFirst.IsAutoSyncStructure) _orm.CodeFirst.SyncStructure(entityType); + return this; + } - var sb = new StringBuilder(); - sb.Append("UPDATE ").Append(_commonUtils.QuoteSqlName(_tableRule?.Invoke(_table.DbName) ?? _table.DbName)).Append(" SET "); + public string ToSql() + { + if (_where.Length == 0 && _source.Any() == false) return null; - if (_set.Length > 0) { //指定 set 更新 - sb.Append(_set.ToString().Substring(2)); + var sb = new StringBuilder(); + sb.Append("UPDATE ").Append(_commonUtils.QuoteSqlName(_tableRule?.Invoke(_table.DbName) ?? _table.DbName)).Append(" SET "); - } else if (_source.Count == 1) { //保存 Source - _paramsSource.Clear(); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (col.Attribute.IsIdentity == false && col.Attribute.IsVersion == false && _ignore.ContainsKey(col.Attribute.Name) == false) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = "); - var value = col.GetMapValue(_source.First()); - if (_noneParameter) { - sb.Append(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, col.Attribute.MapType, value)); - } else { - sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"p_{_paramsSource.Count}"))); - _commonUtils.AppendParamter(_paramsSource, null, col.Attribute.MapType, value); - } - ++colidx; - } - } - if (colidx == 0) return null; + if (_set.Length > 0) + { //指定 set 更新 + sb.Append(_set.ToString().Substring(2)); - } else if (_source.Count > 1) { //批量保存 Source - if (_table.Primarys.Any() == false) return null; + } + else if (_source.Count == 1) + { //保存 Source + _paramsSource.Clear(); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (col.Attribute.IsIdentity == false && col.Attribute.IsVersion == false && _ignore.ContainsKey(col.Attribute.Name) == false) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = "); + var value = col.GetMapValue(_source.First()); + if (_noneParameter) + { + sb.Append(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, col.Attribute.MapType, value)); + } + else + { + sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"p_{_paramsSource.Count}"))); + _commonUtils.AppendParamter(_paramsSource, null, col.Attribute.MapType, value); + } + ++colidx; + } + } + if (colidx == 0) return null; - var caseWhen = new StringBuilder(); - caseWhen.Append("CASE "); - ToSqlCase(caseWhen, _table.Primarys); - var cw = caseWhen.ToString(); + } + else if (_source.Count > 1) + { //批量保存 Source + if (_table.Primarys.Any() == false) return null; - _paramsSource.Clear(); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (col.Attribute.IsIdentity == false && col.Attribute.IsVersion == false && _ignore.ContainsKey(col.Attribute.Name) == false) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = "); + var caseWhen = new StringBuilder(); + caseWhen.Append("CASE "); + ToSqlCase(caseWhen, _table.Primarys); + var cw = caseWhen.ToString(); - var isnull = false; - var cwsb = new StringBuilder().Append(cw); - foreach (var d in _source) { - cwsb.Append(" \r\nWHEN "); - ToSqlWhen(cwsb, _table.Primarys, d); - cwsb.Append(" THEN "); - var value = col.GetMapValue(d); - if (_noneParameter) { - cwsb.Append(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, col.Attribute.MapType, value)); - } else { - cwsb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"p_{_paramsSource.Count}"))); - _commonUtils.AppendParamter(_paramsSource, null, col.Attribute.MapType, value); - } - if (isnull == false) isnull = value == null || value == DBNull.Value; - } - cwsb.Append(" END"); - if (isnull == false) sb.Append(cwsb.ToString()); - else sb.Append("NULL"); - cwsb.Clear(); + _paramsSource.Clear(); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (col.Attribute.IsIdentity == false && col.Attribute.IsVersion == false && _ignore.ContainsKey(col.Attribute.Name) == false) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)).Append(" = "); - ++colidx; - } - } - if (colidx == 0) return null; - } else if (_setIncr.Length == 0) - return null; + var isnull = false; + var cwsb = new StringBuilder().Append(cw); + foreach (var d in _source) + { + cwsb.Append(" \r\nWHEN "); + ToSqlWhen(cwsb, _table.Primarys, d); + cwsb.Append(" THEN "); + var value = col.GetMapValue(d); + if (_noneParameter) + { + cwsb.Append(_commonUtils.GetNoneParamaterSqlValue(_paramsSource, col.Attribute.MapType, value)); + } + else + { + cwsb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"p_{_paramsSource.Count}"))); + _commonUtils.AppendParamter(_paramsSource, null, col.Attribute.MapType, value); + } + if (isnull == false) isnull = value == null || value == DBNull.Value; + } + cwsb.Append(" END"); + if (isnull == false) sb.Append(cwsb.ToString()); + else sb.Append("NULL"); + cwsb.Clear(); - if (_setIncr.Length > 0) - sb.Append(_set.Length > 0 ? _setIncr.ToString() : _setIncr.ToString().Substring(2)); + ++colidx; + } + } + if (colidx == 0) return null; + } + else if (_setIncr.Length == 0) + return null; - if (_table.VersionColumn != null) { - var vcname = _commonUtils.QuoteSqlName(_table.VersionColumn.Attribute.Name); - sb.Append(", ").Append(vcname).Append(" = ").Append(vcname).Append(" + 1"); - } + if (_setIncr.Length > 0) + sb.Append(_set.Length > 0 ? _setIncr.ToString() : _setIncr.ToString().Substring(2)); - sb.Append(" \r\nWHERE "); - if (_source.Any()) - sb.Append("(").Append(_commonUtils.WhereItems(_table, "", _source)).Append(")"); + if (_table.VersionColumn != null) + { + var vcname = _commonUtils.QuoteSqlName(_table.VersionColumn.Attribute.Name); + sb.Append(", ").Append(vcname).Append(" = ").Append(vcname).Append(" + 1"); + } - if (_where.Length > 0) - sb.Append(_source.Any() ? _where.ToString() : _where.ToString().Substring(5)); + sb.Append(" \r\nWHERE "); + if (_source.Any()) + sb.Append("(").Append(_commonUtils.WhereItems(_table, "", _source)).Append(")"); - if (_table.VersionColumn != null) { - var versionCondi = WhereCaseSource(_table.VersionColumn.CsName, sqlval => sqlval); - if (string.IsNullOrEmpty(versionCondi) == false) - sb.Append(" AND ").Append(versionCondi); - } + if (_where.Length > 0) + sb.Append(_source.Any() ? _where.ToString() : _where.ToString().Substring(5)); - return sb.ToString(); - } - } + if (_table.VersionColumn != null) + { + var versionCondi = WhereCaseSource(_table.VersionColumn.CsName, sqlval => sqlval); + if (string.IsNullOrEmpty(versionCondi) == false) + sb.Append(" AND ").Append(versionCondi); + } + + return sb.ToString(); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/CommonUtils.cs b/FreeSql/Internal/CommonUtils.cs index c16f0104..132ce338 100644 --- a/FreeSql/Internal/CommonUtils.cs +++ b/FreeSql/Internal/CommonUtils.cs @@ -17,293 +17,339 @@ using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; -namespace FreeSql.Internal { - public abstract class CommonUtils { +namespace FreeSql.Internal +{ + public abstract class CommonUtils + { - public abstract string GetNoneParamaterSqlValue(List specialParams, Type type, object value); - public abstract DbParameter AppendParamter(List _params, string parameterName, Type type, object value); - public abstract DbParameter[] GetDbParamtersByObject(string sql, object obj); - public abstract string FormatSql(string sql, params object[] args); - public abstract string QuoteSqlName(string name); - public abstract string TrimQuoteSqlName(string name); - public abstract string QuoteParamterName(string name); - public abstract string IsNull(string sql, object value); - public abstract string StringConcat(string[] objs, Type[] types); - public abstract string Mod(string left, string right, Type leftType, Type rightType); - public abstract string QuoteWriteParamter(Type type, string paramterName); - public abstract string QuoteReadColumn(Type type, string columnName); + public abstract string GetNoneParamaterSqlValue(List specialParams, Type type, object value); + public abstract DbParameter AppendParamter(List _params, string parameterName, Type type, object value); + public abstract DbParameter[] GetDbParamtersByObject(string sql, object obj); + public abstract string FormatSql(string sql, params object[] args); + public abstract string QuoteSqlName(string name); + public abstract string TrimQuoteSqlName(string name); + public abstract string QuoteParamterName(string name); + public abstract string IsNull(string sql, object value); + public abstract string StringConcat(string[] objs, Type[] types); + public abstract string Mod(string left, string right, Type leftType, Type rightType); + public abstract string QuoteWriteParamter(Type type, string paramterName); + public abstract string QuoteReadColumn(Type type, string columnName); - public IFreeSql _orm { get; set; } - public ICodeFirst CodeFirst => _orm.CodeFirst; - public TableInfo GetTableByEntity(Type entity) => Utils.GetTableByEntity(entity, this); - public List dbTables { get; set; } - public object dbTablesLock = new object(); + public IFreeSql _orm { get; set; } + public ICodeFirst CodeFirst => _orm.CodeFirst; + public TableInfo GetTableByEntity(Type entity) => Utils.GetTableByEntity(entity, this); + public List dbTables { get; set; } + public object dbTablesLock = new object(); - public CommonUtils(IFreeSql orm) { - _orm = orm; - } + public CommonUtils(IFreeSql orm) + { + _orm = orm; + } - ConcurrentDictionary dicConfigEntity = new ConcurrentDictionary(); - public ICodeFirst ConfigEntity(Action> entity) { - if (entity == null) return _orm.CodeFirst; - var type = typeof(T); - var table = dicConfigEntity.GetOrAdd(type, new TableAttribute()); - var fluent = new TableFluent(table); - entity.Invoke(fluent); - Utils.RemoveTableByEntity(type, this); //remove cache - return _orm.CodeFirst; - } - public ICodeFirst ConfigEntity(Type type, Action entity) { - if (entity == null) return _orm.CodeFirst; - var table = dicConfigEntity.GetOrAdd(type, new TableAttribute()); - var fluent = new TableFluent(type, table); - entity.Invoke(fluent); - Utils.RemoveTableByEntity(type, this); //remove cache - return _orm.CodeFirst; - } - public TableAttribute GetConfigEntity(Type type) { - return dicConfigEntity.TryGetValue(type, out var trytb) ? trytb : null; - } - public TableAttribute GetEntityTableAttribute(Type type) { - TableAttribute attr = null; - if (_orm.Aop.ConfigEntity != null) { - var aope = new Aop.ConfigEntityEventArgs(type); - _orm.Aop.ConfigEntity(_orm, aope); - attr = aope.ModifyResult; - } - if (attr == null) attr = new TableAttribute(); - if (dicConfigEntity.TryGetValue(type, out var trytb)) { - if (!string.IsNullOrEmpty(trytb.Name)) attr.Name = trytb.Name; - if (!string.IsNullOrEmpty(trytb.OldName)) attr.OldName = trytb.OldName; - if (!string.IsNullOrEmpty(trytb.SelectFilter)) attr.SelectFilter = trytb.SelectFilter; - if (trytb._DisableSyncStructure != null) attr._DisableSyncStructure = trytb.DisableSyncStructure; + ConcurrentDictionary dicConfigEntity = new ConcurrentDictionary(); + public ICodeFirst ConfigEntity(Action> entity) + { + if (entity == null) return _orm.CodeFirst; + var type = typeof(T); + var table = dicConfigEntity.GetOrAdd(type, new TableAttribute()); + var fluent = new TableFluent(table); + entity.Invoke(fluent); + Utils.RemoveTableByEntity(type, this); //remove cache + return _orm.CodeFirst; + } + public ICodeFirst ConfigEntity(Type type, Action entity) + { + if (entity == null) return _orm.CodeFirst; + var table = dicConfigEntity.GetOrAdd(type, new TableAttribute()); + var fluent = new TableFluent(type, table); + entity.Invoke(fluent); + Utils.RemoveTableByEntity(type, this); //remove cache + return _orm.CodeFirst; + } + public TableAttribute GetConfigEntity(Type type) + { + return dicConfigEntity.TryGetValue(type, out var trytb) ? trytb : null; + } + public TableAttribute GetEntityTableAttribute(Type type) + { + TableAttribute attr = null; + if (_orm.Aop.ConfigEntity != null) + { + var aope = new Aop.ConfigEntityEventArgs(type); + _orm.Aop.ConfigEntity(_orm, aope); + attr = aope.ModifyResult; + } + if (attr == null) attr = new TableAttribute(); + if (dicConfigEntity.TryGetValue(type, out var trytb)) + { + if (!string.IsNullOrEmpty(trytb.Name)) attr.Name = trytb.Name; + if (!string.IsNullOrEmpty(trytb.OldName)) attr.OldName = trytb.OldName; + if (!string.IsNullOrEmpty(trytb.SelectFilter)) attr.SelectFilter = trytb.SelectFilter; + if (trytb._DisableSyncStructure != null) attr._DisableSyncStructure = trytb.DisableSyncStructure; - } - var attrs = type.GetCustomAttributes(typeof(TableAttribute), false); - foreach (var tryattrobj in attrs) { - var tryattr = tryattrobj as TableAttribute; - if (tryattr == null) continue; - if (!string.IsNullOrEmpty(tryattr.Name)) attr.Name = tryattr.Name; - if (!string.IsNullOrEmpty(tryattr.OldName)) attr.OldName = tryattr.OldName; - if (!string.IsNullOrEmpty(tryattr.SelectFilter)) attr.SelectFilter = tryattr.SelectFilter; - if (tryattr._DisableSyncStructure != null) attr._DisableSyncStructure = tryattr.DisableSyncStructure; - } - if (!string.IsNullOrEmpty(attr.Name)) return attr; - if (!string.IsNullOrEmpty(attr.OldName)) return attr; - if (!string.IsNullOrEmpty(attr.SelectFilter)) return attr; - if (attr._DisableSyncStructure != null) return attr; - return null; - } - public ColumnAttribute GetEntityColumnAttribute(Type type, PropertyInfo proto) { - ColumnAttribute attr = null; - if (_orm.Aop.ConfigEntityProperty != null) { - var aope = new Aop.ConfigEntityPropertyEventArgs(type, proto); - _orm.Aop.ConfigEntityProperty(_orm, aope); - attr = aope.ModifyResult; - } - if (attr == null) attr = new ColumnAttribute(); - if (dicConfigEntity.TryGetValue(type, out var trytb) && trytb._columns.TryGetValue(proto.Name, out var trycol)) { - if (!string.IsNullOrEmpty(trycol.Name)) attr.Name = trycol.Name; - if (!string.IsNullOrEmpty(trycol.OldName)) attr.OldName = trycol.OldName; - if (!string.IsNullOrEmpty(trycol.DbType)) attr.DbType = trycol.DbType; - if (trycol._IsPrimary != null) attr._IsPrimary = trycol.IsPrimary; - if (trycol._IsIdentity != null) attr._IsIdentity = trycol.IsIdentity; - if (trycol._IsNullable != null) attr._IsNullable = trycol.IsNullable; - if (trycol._IsIgnore != null) attr._IsIgnore = trycol.IsIgnore; - if (trycol._IsVersion != null) attr._IsVersion = trycol.IsVersion; - if (trycol._Uniques != null) attr._Uniques = trycol._Uniques; - if (trycol.MapType != null) attr.MapType = trycol.MapType; - if (trycol.DbDefautValue != null) attr.DbDefautValue = trycol.DbDefautValue; - } - var attrs = proto.GetCustomAttributes(typeof(ColumnAttribute), false); - foreach (var tryattrobj in attrs) { - var tryattr = tryattrobj as ColumnAttribute; - if (tryattr == null) continue; - if (!string.IsNullOrEmpty(tryattr.Name)) attr.Name = tryattr.Name; - if (!string.IsNullOrEmpty(tryattr.OldName)) attr.OldName = tryattr.OldName; - if (!string.IsNullOrEmpty(tryattr.DbType)) attr.DbType = tryattr.DbType; - if (tryattr._IsPrimary != null) attr._IsPrimary = tryattr.IsPrimary; - if (tryattr._IsIdentity != null) attr._IsIdentity = tryattr.IsIdentity; - if (tryattr._IsNullable != null) attr._IsNullable = tryattr.IsNullable; - if (tryattr._IsIgnore != null) attr._IsIgnore = tryattr.IsIgnore; - if (tryattr._IsVersion != null) attr._IsVersion = tryattr.IsVersion; - if (tryattr._Uniques != null) attr._Uniques = tryattr._Uniques; - if (tryattr.MapType != null) attr.MapType = tryattr.MapType; - if (tryattr.DbDefautValue != null) attr.DbDefautValue = tryattr.DbDefautValue; - } - ColumnAttribute ret = null; - if (!string.IsNullOrEmpty(attr.Name)) ret = attr; - if (!string.IsNullOrEmpty(attr.OldName)) ret = attr; - if (!string.IsNullOrEmpty(attr.DbType)) ret = attr; - if (attr._IsPrimary != null) ret = attr; - if (attr._IsIdentity != null) ret = attr; - if (attr._IsNullable != null) ret = attr; - if (attr._IsIgnore != null) ret = attr; - if (attr._IsVersion != null) ret = attr; - if (attr._Uniques != null) ret = attr; - if (attr.MapType != null) ret = attr; - if (attr.DbDefautValue != null) ret = attr; - if (ret != null && ret.MapType == null) ret.MapType = proto.PropertyType; - return ret; - } + } + var attrs = type.GetCustomAttributes(typeof(TableAttribute), false); + foreach (var tryattrobj in attrs) + { + var tryattr = tryattrobj as TableAttribute; + if (tryattr == null) continue; + if (!string.IsNullOrEmpty(tryattr.Name)) attr.Name = tryattr.Name; + if (!string.IsNullOrEmpty(tryattr.OldName)) attr.OldName = tryattr.OldName; + if (!string.IsNullOrEmpty(tryattr.SelectFilter)) attr.SelectFilter = tryattr.SelectFilter; + if (tryattr._DisableSyncStructure != null) attr._DisableSyncStructure = tryattr.DisableSyncStructure; + } + if (!string.IsNullOrEmpty(attr.Name)) return attr; + if (!string.IsNullOrEmpty(attr.OldName)) return attr; + if (!string.IsNullOrEmpty(attr.SelectFilter)) return attr; + if (attr._DisableSyncStructure != null) return attr; + return null; + } + public ColumnAttribute GetEntityColumnAttribute(Type type, PropertyInfo proto) + { + ColumnAttribute attr = null; + if (_orm.Aop.ConfigEntityProperty != null) + { + var aope = new Aop.ConfigEntityPropertyEventArgs(type, proto); + _orm.Aop.ConfigEntityProperty(_orm, aope); + attr = aope.ModifyResult; + } + if (attr == null) attr = new ColumnAttribute(); + if (dicConfigEntity.TryGetValue(type, out var trytb) && trytb._columns.TryGetValue(proto.Name, out var trycol)) + { + if (!string.IsNullOrEmpty(trycol.Name)) attr.Name = trycol.Name; + if (!string.IsNullOrEmpty(trycol.OldName)) attr.OldName = trycol.OldName; + if (!string.IsNullOrEmpty(trycol.DbType)) attr.DbType = trycol.DbType; + if (trycol._IsPrimary != null) attr._IsPrimary = trycol.IsPrimary; + if (trycol._IsIdentity != null) attr._IsIdentity = trycol.IsIdentity; + if (trycol._IsNullable != null) attr._IsNullable = trycol.IsNullable; + if (trycol._IsIgnore != null) attr._IsIgnore = trycol.IsIgnore; + if (trycol._IsVersion != null) attr._IsVersion = trycol.IsVersion; + if (trycol._Uniques != null) attr._Uniques = trycol._Uniques; + if (trycol.MapType != null) attr.MapType = trycol.MapType; + if (trycol.DbDefautValue != null) attr.DbDefautValue = trycol.DbDefautValue; + } + var attrs = proto.GetCustomAttributes(typeof(ColumnAttribute), false); + foreach (var tryattrobj in attrs) + { + var tryattr = tryattrobj as ColumnAttribute; + if (tryattr == null) continue; + if (!string.IsNullOrEmpty(tryattr.Name)) attr.Name = tryattr.Name; + if (!string.IsNullOrEmpty(tryattr.OldName)) attr.OldName = tryattr.OldName; + if (!string.IsNullOrEmpty(tryattr.DbType)) attr.DbType = tryattr.DbType; + if (tryattr._IsPrimary != null) attr._IsPrimary = tryattr.IsPrimary; + if (tryattr._IsIdentity != null) attr._IsIdentity = tryattr.IsIdentity; + if (tryattr._IsNullable != null) attr._IsNullable = tryattr.IsNullable; + if (tryattr._IsIgnore != null) attr._IsIgnore = tryattr.IsIgnore; + if (tryattr._IsVersion != null) attr._IsVersion = tryattr.IsVersion; + if (tryattr._Uniques != null) attr._Uniques = tryattr._Uniques; + if (tryattr.MapType != null) attr.MapType = tryattr.MapType; + if (tryattr.DbDefautValue != null) attr.DbDefautValue = tryattr.DbDefautValue; + } + ColumnAttribute ret = null; + if (!string.IsNullOrEmpty(attr.Name)) ret = attr; + if (!string.IsNullOrEmpty(attr.OldName)) ret = attr; + if (!string.IsNullOrEmpty(attr.DbType)) ret = attr; + if (attr._IsPrimary != null) ret = attr; + if (attr._IsIdentity != null) ret = attr; + if (attr._IsNullable != null) ret = attr; + if (attr._IsIgnore != null) ret = attr; + if (attr._IsVersion != null) ret = attr; + if (attr._Uniques != null) ret = attr; + if (attr.MapType != null) ret = attr; + if (attr.DbDefautValue != null) ret = attr; + if (ret != null && ret.MapType == null) ret.MapType = proto.PropertyType; + return ret; + } - public string WhereObject(TableInfo table, string aliasAndDot, object dywhere) { - if (dywhere == null) return ""; - var type = dywhere.GetType(); - var primarys = table.Primarys; - var pk1 = primarys.FirstOrDefault(); - if (primarys.Length == 1 && (type == pk1.CsType || type.IsNumberType() && pk1.CsType.IsNumberType())) { - return $"{aliasAndDot}{this.QuoteSqlName(pk1.Attribute.Name)} = {this.FormatSql("{0}", Utils.GetDataReaderValue(pk1.Attribute.MapType, dywhere))}"; - } else if (primarys.Length > 0 && (type == table.Type || type.BaseType == table.Type)) { - var sb = new StringBuilder(); - var pkidx = 0; - foreach (var pk in primarys) { - if (pkidx > 0) sb.Append(" AND "); - sb.Append(aliasAndDot).Append(this.QuoteSqlName(pk.Attribute.Name)); - sb.Append(this.FormatSql(" = {0}", pk.GetMapValue(dywhere))); - ++pkidx; - } - return sb.ToString(); - } else if (dywhere is IEnumerable) { - var sb = new StringBuilder(); - var ie = dywhere as IEnumerable; - var ieidx = 0; - foreach (var i in ie) { - var fw = WhereObject(table, aliasAndDot, i); - if (string.IsNullOrEmpty(fw)) continue; - if (ieidx > 0) sb.Append(" OR "); - sb.Append(fw); - ++ieidx; - } - return sb.ToString(); - } else { - var sb = new StringBuilder(); - var ps = type.GetProperties(); - var psidx = 0; - foreach (var p in ps) { - if (table.Columns.TryGetValue(p.Name, out var trycol) == false) continue; - if (psidx > 0) sb.Append(" AND "); - sb.Append(aliasAndDot).Append(this.QuoteSqlName(trycol.Attribute.Name)); - sb.Append(this.FormatSql(" = {0}", Utils.GetDataReaderValue(trycol.Attribute.MapType, p.GetValue(dywhere)))); - ++psidx; - } - if (psidx == 0) return ""; - return sb.ToString(); - } - } + public string WhereObject(TableInfo table, string aliasAndDot, object dywhere) + { + if (dywhere == null) return ""; + var type = dywhere.GetType(); + var primarys = table.Primarys; + var pk1 = primarys.FirstOrDefault(); + if (primarys.Length == 1 && (type == pk1.CsType || type.IsNumberType() && pk1.CsType.IsNumberType())) + { + return $"{aliasAndDot}{this.QuoteSqlName(pk1.Attribute.Name)} = {this.FormatSql("{0}", Utils.GetDataReaderValue(pk1.Attribute.MapType, dywhere))}"; + } + else if (primarys.Length > 0 && (type == table.Type || type.BaseType == table.Type)) + { + var sb = new StringBuilder(); + var pkidx = 0; + foreach (var pk in primarys) + { + if (pkidx > 0) sb.Append(" AND "); + sb.Append(aliasAndDot).Append(this.QuoteSqlName(pk.Attribute.Name)); + sb.Append(this.FormatSql(" = {0}", pk.GetMapValue(dywhere))); + ++pkidx; + } + return sb.ToString(); + } + else if (dywhere is IEnumerable) + { + var sb = new StringBuilder(); + var ie = dywhere as IEnumerable; + var ieidx = 0; + foreach (var i in ie) + { + var fw = WhereObject(table, aliasAndDot, i); + if (string.IsNullOrEmpty(fw)) continue; + if (ieidx > 0) sb.Append(" OR "); + sb.Append(fw); + ++ieidx; + } + return sb.ToString(); + } + else + { + var sb = new StringBuilder(); + var ps = type.GetProperties(); + var psidx = 0; + foreach (var p in ps) + { + if (table.Columns.TryGetValue(p.Name, out var trycol) == false) continue; + if (psidx > 0) sb.Append(" AND "); + sb.Append(aliasAndDot).Append(this.QuoteSqlName(trycol.Attribute.Name)); + sb.Append(this.FormatSql(" = {0}", Utils.GetDataReaderValue(trycol.Attribute.MapType, p.GetValue(dywhere)))); + ++psidx; + } + if (psidx == 0) return ""; + return sb.ToString(); + } + } - public string WhereItems(TableInfo table, string aliasAndDot, IEnumerable items) { - if (items == null || items.Any() == false) return null; - if (table.Primarys.Any() == false) return null; - var its = items.Where(a => a != null).ToArray(); + public string WhereItems(TableInfo table, string aliasAndDot, IEnumerable items) + { + if (items == null || items.Any() == false) return null; + if (table.Primarys.Any() == false) return null; + var its = items.Where(a => a != null).ToArray(); - var pk1 = table.Primarys.FirstOrDefault(); - if (table.Primarys.Length == 1) { - var sbin = new StringBuilder(); - sbin.Append(aliasAndDot).Append(this.QuoteSqlName(pk1.Attribute.Name)); - var indt = its.Select(a => pk1.GetMapValue(a)).Where(a => a != null).ToArray(); - if (indt.Any() == false) return null; - if (indt.Length == 1) sbin.Append(" = ").Append(this.FormatSql("{0}", indt.First())); - else sbin.Append(" IN (").Append(string.Join(",", indt.Select(a => this.FormatSql("{0}", a)))).Append(")"); - return sbin.ToString(); - } - var dicpk = its.Length > 5 ? new Dictionary() : null; - var sb = its.Length > 5 ? null : new StringBuilder(); - var iidx = 0; - foreach (var item in its) { - var filter = ""; - foreach (var pk in table.Primarys) - filter += $" AND {aliasAndDot}{this.QuoteSqlName(pk.Attribute.Name)} = {this.FormatSql("{0}", pk.GetMapValue(item))}"; - if (string.IsNullOrEmpty(filter)) continue; - if (sb != null) { - sb.Append(" OR ("); - sb.Append(filter.Substring(5)); - sb.Append(")"); - ++iidx; - } - if (dicpk != null) { - filter = filter.Substring(5); - if (dicpk.ContainsKey(filter) == false) { - dicpk.Add(filter, true); - ++iidx; - } - } - //++iidx; - } - if (iidx == 0) return null; - if (sb == null) { - sb = new StringBuilder(); - foreach (var fil in dicpk) { - sb.Append(" OR ("); - sb.Append(fil.Key); - sb.Append(")"); - } - } - return iidx == 1 ? sb.Remove(0, 5).Remove(sb.Length - 1, 1).ToString() : sb.Remove(0, 4).ToString(); - } + var pk1 = table.Primarys.FirstOrDefault(); + if (table.Primarys.Length == 1) + { + var sbin = new StringBuilder(); + sbin.Append(aliasAndDot).Append(this.QuoteSqlName(pk1.Attribute.Name)); + var indt = its.Select(a => pk1.GetMapValue(a)).Where(a => a != null).ToArray(); + if (indt.Any() == false) return null; + if (indt.Length == 1) sbin.Append(" = ").Append(this.FormatSql("{0}", indt.First())); + else sbin.Append(" IN (").Append(string.Join(",", indt.Select(a => this.FormatSql("{0}", a)))).Append(")"); + return sbin.ToString(); + } + var dicpk = its.Length > 5 ? new Dictionary() : null; + var sb = its.Length > 5 ? null : new StringBuilder(); + var iidx = 0; + foreach (var item in its) + { + var filter = ""; + foreach (var pk in table.Primarys) + filter += $" AND {aliasAndDot}{this.QuoteSqlName(pk.Attribute.Name)} = {this.FormatSql("{0}", pk.GetMapValue(item))}"; + if (string.IsNullOrEmpty(filter)) continue; + if (sb != null) + { + sb.Append(" OR ("); + sb.Append(filter.Substring(5)); + sb.Append(")"); + ++iidx; + } + if (dicpk != null) + { + filter = filter.Substring(5); + if (dicpk.ContainsKey(filter) == false) + { + dicpk.Add(filter, true); + ++iidx; + } + } + //++iidx; + } + if (iidx == 0) return null; + if (sb == null) + { + sb = new StringBuilder(); + foreach (var fil in dicpk) + { + sb.Append(" OR ("); + sb.Append(fil.Key); + sb.Append(")"); + } + } + return iidx == 1 ? sb.Remove(0, 5).Remove(sb.Length - 1, 1).ToString() : sb.Remove(0, 4).ToString(); + } - /// - /// 通过属性的注释文本,通过 xml 读取 - /// - /// - /// Dict:key=属性名,value=注释 - public static Dictionary GetProperyCommentBySummary(Type type) { - var xmlPath = type.Assembly.Location.Replace(".dll", ".xml"); - if (File.Exists(xmlPath) == false) return null; + /// + /// 通过属性的注释文本,通过 xml 读取 + /// + /// + /// Dict:key=属性名,value=注释 + public static Dictionary GetProperyCommentBySummary(Type type) + { + var xmlPath = type.Assembly.Location.Replace(".dll", ".xml"); + if (File.Exists(xmlPath) == false) return null; - var dic = new Dictionary(); - var className = type.IsNested ? $"{type.Namespace}.{type.DeclaringType.Name}.{type.Name}" : $"{type.Namespace}.{type.Name}"; - var sReader = new StringReader(File.ReadAllText(xmlPath)); - using (var xmlReader = XmlReader.Create(sReader)) { - var xpath = new XPathDocument(xmlReader); - var xmlNav = xpath.CreateNavigator(); + var dic = new Dictionary(); + var className = type.IsNested ? $"{type.Namespace}.{type.DeclaringType.Name}.{type.Name}" : $"{type.Namespace}.{type.Name}"; + var sReader = new StringReader(File.ReadAllText(xmlPath)); + using (var xmlReader = XmlReader.Create(sReader)) + { + var xpath = new XPathDocument(xmlReader); + var xmlNav = xpath.CreateNavigator(); - var props = type.GetProperties(); - foreach (var prop in props) { - var node = xmlNav.SelectSingleNode($"/doc/members/member[@name='P:{className}.{prop.Name}']/summary"); - if (node == null) continue; - var comment = node.InnerXml.Trim(' ', '\r', '\n', '\t'); - if (string.IsNullOrEmpty(comment)) continue; + var props = type.GetProperties(); + foreach (var prop in props) + { + var node = xmlNav.SelectSingleNode($"/doc/members/member[@name='P:{className}.{prop.Name}']/summary"); + if (node == null) continue; + var comment = node.InnerXml.Trim(' ', '\r', '\n', '\t'); + if (string.IsNullOrEmpty(comment)) continue; - dic.Add(prop.Name, comment); - } - } + dic.Add(prop.Name, comment); + } + } - return dic; - } + return dic; + } - public static void PrevReheatConnectionPool(ObjectPool pool, int minPoolSize) { - if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize); - if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize; - var initTestOk = true; - var initStartTime = DateTime.Now; - var initConns = new ConcurrentBag>(); + public static void PrevReheatConnectionPool(ObjectPool pool, int minPoolSize) + { + if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize); + if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize; + var initTestOk = true; + var initStartTime = DateTime.Now; + var initConns = new ConcurrentBag>(); - try { - var conn = pool.Get(); - initConns.Add(conn); - pool.Policy.OnCheckAvailable(conn); - } catch { - initTestOk = false; //预热一次失败,后面将不进行 - } - for (var a = 1; initTestOk && a < minPoolSize; a += 10) { - if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出 - var b = Math.Min(minPoolSize - a, 10); //每10个预热 - var initTasks = new Task[b]; - for (var c = 0; c < b; c++) { - initTasks[c] = Task.Run(() => { - try { - var conn = pool.Get(); - initConns.Add(conn); - pool.Policy.OnCheckAvailable(conn); - } catch { - initTestOk = false; //有失败,下一组退出预热 - } - }); - } - Task.WaitAll(initTasks); - } - while (initConns.TryTake(out var conn)) pool.Return(conn); - } - } + try + { + var conn = pool.Get(); + initConns.Add(conn); + pool.Policy.OnCheckAvailable(conn); + } + catch + { + initTestOk = false; //预热一次失败,后面将不进行 + } + for (var a = 1; initTestOk && a < minPoolSize; a += 10) + { + if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出 + var b = Math.Min(minPoolSize - a, 10); //每10个预热 + var initTasks = new Task[b]; + for (var c = 0; c < b; c++) + { + initTasks[c] = Task.Run(() => + { + try + { + var conn = pool.Get(); + initConns.Add(conn); + pool.Policy.OnCheckAvailable(conn); + } + catch + { + initTestOk = false; //有失败,下一组退出预热 + } + }); + } + Task.WaitAll(initTasks); + } + while (initConns.TryTake(out var conn)) pool.Return(conn); + } + } } diff --git a/FreeSql/Internal/Model/ColumnInfo.cs b/FreeSql/Internal/Model/ColumnInfo.cs index fe17b231..8ff71303 100644 --- a/FreeSql/Internal/Model/ColumnInfo.cs +++ b/FreeSql/Internal/Model/ColumnInfo.cs @@ -4,71 +4,77 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq.Expressions; -namespace FreeSql.Internal.Model { - public class ColumnInfo { - public TableInfo Table { get; set; } - public string CsName { get; set; } - public Type CsType { get; set; } - public ColumnAttribute Attribute { get; set; } - public string Comment { get; internal set; } +namespace FreeSql.Internal.Model +{ + public class ColumnInfo + { + public TableInfo Table { get; set; } + public string CsName { get; set; } + public Type CsType { get; set; } + public ColumnAttribute Attribute { get; set; } + public string Comment { get; internal set; } - static ConcurrentDictionary> _dicGetMapValue = new ConcurrentDictionary>(); - public object GetMapValue(object obj) { - var func = _dicGetMapValue.GetOrAdd(this, col => { - var paramExp = Expression.Parameter(typeof(object)); - var returnTarget = Expression.Label(typeof(object)); + static ConcurrentDictionary> _dicGetMapValue = new ConcurrentDictionary>(); + public object GetMapValue(object obj) + { + var func = _dicGetMapValue.GetOrAdd(this, col => + { + var paramExp = Expression.Parameter(typeof(object)); + var returnTarget = Expression.Label(typeof(object)); - if (Attribute.MapType == CsType) - return Expression.Lambda>( - Expression.Block( - Expression.Return(returnTarget, Expression.Convert( - Expression.MakeMemberAccess( - Expression.TypeAs(paramExp, col.Table.Type), - Table.Properties[col.CsName] - ), typeof(object))), - Expression.Label(returnTarget, Expression.Default(typeof(object))) - ), new[] { paramExp }).Compile(); + if (Attribute.MapType == CsType) + return Expression.Lambda>( + Expression.Block( + Expression.Return(returnTarget, Expression.Convert( + Expression.MakeMemberAccess( + Expression.TypeAs(paramExp, col.Table.Type), + Table.Properties[col.CsName] + ), typeof(object))), + Expression.Label(returnTarget, Expression.Default(typeof(object))) + ), new[] { paramExp }).Compile(); - var retExp = Expression.Variable(typeof(object), "ret"); - var blockExp = new List(); - blockExp.AddRange(new Expression[] { - Expression.Assign(retExp, Utils.GetDataReaderValueBlockExpression(Attribute.MapType, - Expression.MakeMemberAccess( - Expression.TypeAs(paramExp, col.Table.Type), - Table.Properties[col.CsName] - ) - )), - Expression.Return(returnTarget, retExp), - Expression.Label(returnTarget, Expression.Default(typeof(object))) - }); - return Expression.Lambda>(Expression.Block(new[] { retExp }, blockExp), new[] { paramExp }).Compile(); - }); - return func(obj); - } - static ConcurrentDictionary> _dicSetMapValue = new ConcurrentDictionary>(); - public void SetMapValue(object obj, object val) { - var func = _dicSetMapValue.GetOrAdd(this, col => { - var objExp = Expression.Parameter(typeof(object), "obj"); - var valExp = Expression.Parameter(typeof(object), "val"); + var retExp = Expression.Variable(typeof(object), "ret"); + var blockExp = new List(); + blockExp.AddRange(new Expression[] { + Expression.Assign(retExp, Utils.GetDataReaderValueBlockExpression(Attribute.MapType, + Expression.MakeMemberAccess( + Expression.TypeAs(paramExp, col.Table.Type), + Table.Properties[col.CsName] + ) + )), + Expression.Return(returnTarget, retExp), + Expression.Label(returnTarget, Expression.Default(typeof(object))) + }); + return Expression.Lambda>(Expression.Block(new[] { retExp }, blockExp), new[] { paramExp }).Compile(); + }); + return func(obj); + } + static ConcurrentDictionary> _dicSetMapValue = new ConcurrentDictionary>(); + public void SetMapValue(object obj, object val) + { + var func = _dicSetMapValue.GetOrAdd(this, col => + { + var objExp = Expression.Parameter(typeof(object), "obj"); + var valExp = Expression.Parameter(typeof(object), "val"); - if (Attribute.MapType == CsType) - return Expression.Lambda>( - Expression.Assign(Expression.MakeMemberAccess( - Expression.TypeAs(objExp, col.Table.Type), - Table.Properties[col.CsName] - ), Expression.Convert( - valExp, - Attribute.MapType)), objExp, valExp).Compile(); + if (Attribute.MapType == CsType) + return Expression.Lambda>( + Expression.Assign(Expression.MakeMemberAccess( + Expression.TypeAs(objExp, col.Table.Type), + Table.Properties[col.CsName] + ), Expression.Convert( + valExp, + Attribute.MapType)), objExp, valExp).Compile(); - return Expression.Lambda>( - Expression.Assign(Expression.MakeMemberAccess( - Expression.TypeAs(objExp, col.Table.Type), - Table.Properties[col.CsName] - ), Expression.Convert( - Utils.GetDataReaderValueBlockExpression(Attribute.MapType, valExp), - Attribute.MapType)), objExp, valExp).Compile(); - }); - func(obj, val); - } - } + return Expression.Lambda>( + Expression.Assign(Expression.MakeMemberAccess( + Expression.TypeAs(objExp, col.Table.Type), + Table.Properties[col.CsName] + ), Expression.Convert( + Utils.GetDataReaderValueBlockExpression(Attribute.MapType, valExp), + Attribute.MapType)), objExp, valExp).Compile(); + }); + func(obj, val); + } + } } \ No newline at end of file diff --git a/FreeSql/Internal/Model/ReadAnonymousTypeInfo.cs b/FreeSql/Internal/Model/ReadAnonymousTypeInfo.cs index 722fc1b1..d3c1fb3a 100644 --- a/FreeSql/Internal/Model/ReadAnonymousTypeInfo.cs +++ b/FreeSql/Internal/Model/ReadAnonymousTypeInfo.cs @@ -3,17 +3,19 @@ using System.Collections.Generic; using System.Reflection; using System.Text; -namespace FreeSql.Internal.Model { - public class ReadAnonymousTypeInfo { - public PropertyInfo Property { get; set; } - public string CsName { get; set; } - public Type CsType { get; set; } - public Type MapType { get; set; } - public string DbField { get; set; } - public ConstructorInfo Consturctor { get; set; } - public ReadAnonymousTypeInfoConsturctorType ConsturctorType { get; set; } - public List Childs = new List(); - public TableInfo Table { get; set; } - } - public enum ReadAnonymousTypeInfoConsturctorType { Arguments, Properties } +namespace FreeSql.Internal.Model +{ + public class ReadAnonymousTypeInfo + { + public PropertyInfo Property { get; set; } + public string CsName { get; set; } + public Type CsType { get; set; } + public Type MapType { get; set; } + public string DbField { get; set; } + public ConstructorInfo Consturctor { get; set; } + public ReadAnonymousTypeInfoConsturctorType ConsturctorType { get; set; } + public List Childs = new List(); + public TableInfo Table { get; set; } + } + public enum ReadAnonymousTypeInfoConsturctorType { Arguments, Properties } } diff --git a/FreeSql/Internal/Model/SelectColumnInfo.cs b/FreeSql/Internal/Model/SelectColumnInfo.cs index a92947a2..16075a85 100644 --- a/FreeSql/Internal/Model/SelectColumnInfo.cs +++ b/FreeSql/Internal/Model/SelectColumnInfo.cs @@ -2,9 +2,11 @@ using System.Collections.Generic; using System.Text; -namespace FreeSql.Internal.Model { - public class SelectColumnInfo { - public ColumnInfo Column { get; set; } - public SelectTableInfo Table { get; set; } - } +namespace FreeSql.Internal.Model +{ + public class SelectColumnInfo + { + public ColumnInfo Column { get; set; } + public SelectTableInfo Table { get; set; } + } } diff --git a/FreeSql/Internal/Model/SelectTableInfo.cs b/FreeSql/Internal/Model/SelectTableInfo.cs index 0c1d4172..b3e61254 100644 --- a/FreeSql/Internal/Model/SelectTableInfo.cs +++ b/FreeSql/Internal/Model/SelectTableInfo.cs @@ -1,22 +1,26 @@ using System.Linq.Expressions; -namespace FreeSql.Internal.Model { - public class SelectTableInfo { - public TableInfo Table { get; set; } +namespace FreeSql.Internal.Model +{ + public class SelectTableInfo + { + public TableInfo Table { get; set; } - private string _alias; - public string Alias { - get => _alias; - set { - _alias = value; - if (string.IsNullOrEmpty(AliasInit)) AliasInit = value; - } - } - public string AliasInit { get; set; } - public string On { get; set; } - public string NavigateCondition { get; set; } - public ParameterExpression Parameter { get; set; } - public SelectTableInfoType Type { get; set; } - } - public enum SelectTableInfoType { From, LeftJoin, InnerJoin, RightJoin, Parent } + private string _alias; + public string Alias + { + get => _alias; + set + { + _alias = value; + if (string.IsNullOrEmpty(AliasInit)) AliasInit = value; + } + } + public string AliasInit { get; set; } + public string On { get; set; } + public string NavigateCondition { get; set; } + public ParameterExpression Parameter { get; set; } + public SelectTableInfoType Type { get; set; } + } + public enum SelectTableInfoType { From, LeftJoin, InnerJoin, RightJoin, Parent } } diff --git a/FreeSql/Internal/Model/TableInfo.cs b/FreeSql/Internal/Model/TableInfo.cs index c08cfdb7..d1b5bb90 100644 --- a/FreeSql/Internal/Model/TableInfo.cs +++ b/FreeSql/Internal/Model/TableInfo.cs @@ -3,58 +3,65 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; -namespace FreeSql.Internal.Model { - public class TableInfo { - public Type Type { get; set; } - public Type TypeLazy { get; set; } - public MethodInfo TypeLazySetOrm { get; set; } - public Dictionary Properties { get; set; } = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - public Dictionary Columns { get; set; } = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - public Dictionary ColumnsByCs { get; set; } = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - public Dictionary ColumnsByCsIgnore { get; set; } = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - public ColumnInfo[] Primarys { get; set; } - public Dictionary> Uniques { get; set; } - public string CsName { get; set; } - public string DbName { get; set; } - public string DbOldName { get; set; } - public string SelectFilter { get; set; } - public bool DisableSyncStructure { get; set; } +namespace FreeSql.Internal.Model +{ + public class TableInfo + { + public Type Type { get; set; } + public Type TypeLazy { get; set; } + public MethodInfo TypeLazySetOrm { get; set; } + public Dictionary Properties { get; set; } = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + public Dictionary Columns { get; set; } = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + public Dictionary ColumnsByCs { get; set; } = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + public Dictionary ColumnsByCsIgnore { get; set; } = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + public ColumnInfo[] Primarys { get; set; } + public Dictionary> Uniques { get; set; } + public string CsName { get; set; } + public string DbName { get; set; } + public string DbOldName { get; set; } + public string SelectFilter { get; set; } + public bool DisableSyncStructure { get; set; } - public ColumnInfo VersionColumn { get; set; } + public ColumnInfo VersionColumn { get; set; } - ConcurrentDictionary _refs { get; } = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + ConcurrentDictionary _refs { get; } = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - internal void AddOrUpdateTableRef(string propertyName, TableRef tbref) { - _refs.AddOrUpdate(propertyName, tbref, (ok, ov) => tbref); - } - public TableRef GetTableRef(string propertyName, bool isThrowException) { - if (_refs.TryGetValue(propertyName, out var tryref) == false) return null; - if (tryref.Exception != null) { - if (isThrowException) throw tryref.Exception; - return null; - } - return tryref; - } - } + internal void AddOrUpdateTableRef(string propertyName, TableRef tbref) + { + _refs.AddOrUpdate(propertyName, tbref, (ok, ov) => tbref); + } + public TableRef GetTableRef(string propertyName, bool isThrowException) + { + if (_refs.TryGetValue(propertyName, out var tryref) == false) return null; + if (tryref.Exception != null) + { + if (isThrowException) throw tryref.Exception; + return null; + } + return tryref; + } + } - public class TableRef { - public PropertyInfo Property { get; set; } + public class TableRef + { + public PropertyInfo Property { get; set; } - public TableRefType RefType { get; set; } + public TableRefType RefType { get; set; } - public Type RefEntityType { get; set; } - /// - /// 中间表,多对多 - /// - public Type RefMiddleEntityType { get; set; } + public Type RefEntityType { get; set; } + /// + /// 中间表,多对多 + /// + public Type RefMiddleEntityType { get; set; } - public List Columns { get; set; } = new List(); - public List MiddleColumns { get; set; } = new List(); - public List RefColumns { get; set; } = new List(); + public List Columns { get; set; } = new List(); + public List MiddleColumns { get; set; } = new List(); + public List RefColumns { get; set; } = new List(); - public Exception Exception { get; set; } - } - public enum TableRefType { - OneToOne, ManyToOne, OneToMany, ManyToMany - } + public Exception Exception { get; set; } + } + public enum TableRefType + { + OneToOne, ManyToOne, OneToMany, ManyToMany + } } \ No newline at end of file diff --git a/FreeSql/Internal/UtilsExpressionTree.cs b/FreeSql/Internal/UtilsExpressionTree.cs index 1899dcb2..8f3ee4cb 100644 --- a/FreeSql/Internal/UtilsExpressionTree.cs +++ b/FreeSql/Internal/UtilsExpressionTree.cs @@ -12,862 +12,990 @@ using System.Reflection; using System.Text; using System.Text.RegularExpressions; -namespace FreeSql.Internal { - public class Utils { +namespace FreeSql.Internal +{ + public class Utils + { - static ConcurrentDictionary> _cacheGetTableByEntity = new ConcurrentDictionary>(); - internal static void RemoveTableByEntity(Type entity, CommonUtils common) { - if (entity.IsAnonymousType() || - entity.IsValueType || - entity.IsNullableType() || - entity.NullableTypeOrThis() == typeof(BigInteger) - ) return; - var tbc = _cacheGetTableByEntity.GetOrAdd(common._orm.Ado.DataType, k1 => new ConcurrentDictionary()); //区分数据库类型缓存 - if (tbc.TryRemove(entity, out var trytb) && trytb?.TypeLazy != null) tbc.TryRemove(trytb.TypeLazy, out var trylz); - } - internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) { - if (entity.IsAnonymousType() || - entity.IsValueType || - entity.IsNullableType() || - entity.NullableTypeOrThis() == typeof(BigInteger) - ) return null; - var tbc = _cacheGetTableByEntity.GetOrAdd(common._orm.Ado.DataType, k1 => new ConcurrentDictionary()); //区分数据库类型缓存 - if (tbc.TryGetValue(entity, out var trytb)) return trytb; - if (common.CodeFirst.GetDbInfo(entity) != null) return null; - if (typeof(IEnumerable).IsAssignableFrom(entity) && entity.IsGenericParameter == true) return null; - if (entity.IsArray) return null; + static ConcurrentDictionary> _cacheGetTableByEntity = new ConcurrentDictionary>(); + internal static void RemoveTableByEntity(Type entity, CommonUtils common) + { + if (entity.IsAnonymousType() || + entity.IsValueType || + entity.IsNullableType() || + entity.NullableTypeOrThis() == typeof(BigInteger) + ) return; + var tbc = _cacheGetTableByEntity.GetOrAdd(common._orm.Ado.DataType, k1 => new ConcurrentDictionary()); //区分数据库类型缓存 + if (tbc.TryRemove(entity, out var trytb) && trytb?.TypeLazy != null) tbc.TryRemove(trytb.TypeLazy, out var trylz); + } + internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) + { + if (entity.IsAnonymousType() || + entity.IsValueType || + entity.IsNullableType() || + entity.NullableTypeOrThis() == typeof(BigInteger) + ) return null; + var tbc = _cacheGetTableByEntity.GetOrAdd(common._orm.Ado.DataType, k1 => new ConcurrentDictionary()); //区分数据库类型缓存 + if (tbc.TryGetValue(entity, out var trytb)) return trytb; + if (common.CodeFirst.GetDbInfo(entity) != null) return null; + if (typeof(IEnumerable).IsAssignableFrom(entity) && entity.IsGenericParameter == true) return null; + if (entity.IsArray) return null; - var tbattr = common.GetEntityTableAttribute(entity); - trytb = new TableInfo(); - trytb.Type = entity; - trytb.Properties = entity.GetProperties().ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase); - trytb.CsName = entity.Name; - trytb.DbName = (tbattr?.Name ?? entity.Name); - trytb.DbOldName = tbattr?.OldName; - if (common.CodeFirst.IsSyncStructureToLower) { - trytb.DbName = trytb.DbName.ToLower(); - trytb.DbOldName = trytb.DbOldName?.ToLower(); - } - if (common.CodeFirst.IsSyncStructureToUpper) { - trytb.DbName = trytb.DbName.ToUpper(); - trytb.DbOldName = trytb.DbOldName?.ToUpper(); - } - trytb.SelectFilter = tbattr?.SelectFilter; - if (tbattr != null) trytb.DisableSyncStructure = tbattr.DisableSyncStructure; - var propsLazy = new List<(PropertyInfo, bool, bool)>(); - var propsNavObjs = new List(); - var propsComment = CommonUtils.GetProperyCommentBySummary(entity); - foreach (var p in trytb.Properties.Values) { - var setMethod = trytb.Type.GetMethod($"set_{p.Name}"); - var colattr = common.GetEntityColumnAttribute(entity, p); - var tp = common.CodeFirst.GetDbInfo(colattr?.MapType ?? p.PropertyType); - //if (tp == null) continue; - if (tp == null && colattr == null) { - if (common.CodeFirst.IsLazyLoading) { - var getIsVirtual = trytb.Type.GetMethod($"get_{p.Name}")?.IsVirtual; - var setIsVirtual = setMethod?.IsVirtual; - if (getIsVirtual == true || setIsVirtual == true) - propsLazy.Add((p, getIsVirtual == true, setIsVirtual == true)); - } - propsNavObjs.Add(p); - continue; - } - if (colattr == null) - colattr = new ColumnAttribute { - Name = p.Name, - DbType = tp.Value.dbtypeFull, - IsIdentity = false, - IsNullable = tp.Value.isnullable ?? true, - IsPrimary = false, - IsIgnore = false, - Unique = null, - MapType = p.PropertyType - }; - if (colattr._IsNullable == null) colattr._IsNullable = tp?.isnullable; - if (string.IsNullOrEmpty(colattr.DbType)) colattr.DbType = tp?.dbtypeFull ?? "varchar(255)"; - if (colattr.DbType.StartsWith("set(") || colattr.DbType.StartsWith("enum(")) { - var leftBt = colattr.DbType.IndexOf('('); - colattr.DbType = colattr.DbType.Substring(0, leftBt).ToUpper() + colattr.DbType.Substring(leftBt); - } - else - colattr.DbType = colattr.DbType.ToUpper(); + var tbattr = common.GetEntityTableAttribute(entity); + trytb = new TableInfo(); + trytb.Type = entity; + trytb.Properties = entity.GetProperties().ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase); + trytb.CsName = entity.Name; + trytb.DbName = (tbattr?.Name ?? entity.Name); + trytb.DbOldName = tbattr?.OldName; + if (common.CodeFirst.IsSyncStructureToLower) + { + trytb.DbName = trytb.DbName.ToLower(); + trytb.DbOldName = trytb.DbOldName?.ToLower(); + } + if (common.CodeFirst.IsSyncStructureToUpper) + { + trytb.DbName = trytb.DbName.ToUpper(); + trytb.DbOldName = trytb.DbOldName?.ToUpper(); + } + trytb.SelectFilter = tbattr?.SelectFilter; + if (tbattr != null) trytb.DisableSyncStructure = tbattr.DisableSyncStructure; + var propsLazy = new List<(PropertyInfo, bool, bool)>(); + var propsNavObjs = new List(); + var propsComment = CommonUtils.GetProperyCommentBySummary(entity); + foreach (var p in trytb.Properties.Values) + { + var setMethod = trytb.Type.GetMethod($"set_{p.Name}"); + var colattr = common.GetEntityColumnAttribute(entity, p); + var tp = common.CodeFirst.GetDbInfo(colattr?.MapType ?? p.PropertyType); + //if (tp == null) continue; + if (tp == null && colattr == null) + { + if (common.CodeFirst.IsLazyLoading) + { + var getIsVirtual = trytb.Type.GetMethod($"get_{p.Name}")?.IsVirtual; + var setIsVirtual = setMethod?.IsVirtual; + if (getIsVirtual == true || setIsVirtual == true) + propsLazy.Add((p, getIsVirtual == true, setIsVirtual == true)); + } + propsNavObjs.Add(p); + continue; + } + if (colattr == null) + colattr = new ColumnAttribute + { + Name = p.Name, + DbType = tp.Value.dbtypeFull, + IsIdentity = false, + IsNullable = tp.Value.isnullable ?? true, + IsPrimary = false, + IsIgnore = false, + Unique = null, + MapType = p.PropertyType + }; + if (colattr._IsNullable == null) colattr._IsNullable = tp?.isnullable; + if (string.IsNullOrEmpty(colattr.DbType)) colattr.DbType = tp?.dbtypeFull ?? "varchar(255)"; + if (colattr.DbType.StartsWith("set(") || colattr.DbType.StartsWith("enum(")) + { + var leftBt = colattr.DbType.IndexOf('('); + colattr.DbType = colattr.DbType.Substring(0, leftBt).ToUpper() + colattr.DbType.Substring(leftBt); + } + else + colattr.DbType = colattr.DbType.ToUpper(); - if (tp != null && tp.Value.isnullable == null) colattr.IsNullable = tp.Value.dbtypeFull.Contains("NOT NULL") == false; - if (colattr.DbType?.Contains("NOT NULL") == true) colattr.IsNullable = false; - if (string.IsNullOrEmpty(colattr.Name)) colattr.Name = p.Name; - if (common.CodeFirst.IsSyncStructureToLower) { - colattr.Name = colattr.Name.ToLower(); - colattr.Unique = colattr.Unique?.ToLower(); - } - if (common.CodeFirst.IsSyncStructureToUpper) { - colattr.Name = colattr.Name.ToUpper(); - colattr.Unique = colattr.Unique?.ToUpper(); - } + if (tp != null && tp.Value.isnullable == null) colattr.IsNullable = tp.Value.dbtypeFull.Contains("NOT NULL") == false; + if (colattr.DbType?.Contains("NOT NULL") == true) colattr.IsNullable = false; + if (string.IsNullOrEmpty(colattr.Name)) colattr.Name = p.Name; + if (common.CodeFirst.IsSyncStructureToLower) + { + colattr.Name = colattr.Name.ToLower(); + colattr.Unique = colattr.Unique?.ToLower(); + } + if (common.CodeFirst.IsSyncStructureToUpper) + { + colattr.Name = colattr.Name.ToUpper(); + colattr.Unique = colattr.Unique?.ToUpper(); + } - if ((colattr.IsNullable != true || colattr.IsIdentity == true || colattr.IsPrimary == true) && colattr.DbType.Contains("NOT NULL") == false) { - colattr.IsNullable = false; - colattr.DbType += " NOT NULL"; - } - if (colattr.IsNullable == true && colattr.DbType.Contains("NOT NULL")) colattr.DbType = colattr.DbType.Replace("NOT NULL", ""); - colattr.DbType = Regex.Replace(colattr.DbType, @"\([^\)]+\)", m => { - var tmpLt = Regex.Replace(m.Groups[0].Value, @"\s", ""); - if (tmpLt.Contains("CHAR")) tmpLt = tmpLt.Replace("CHAR", " CHAR"); - if (tmpLt.Contains("BYTE")) tmpLt = tmpLt.Replace("BYTE", " BYTE"); - return tmpLt; - }); - if (colattr.IsIdentity == true && colattr.MapType.IsNumberType() == false) - colattr.IsIdentity = false; - if (setMethod == null) colattr.IsIgnore = true; + if ((colattr.IsNullable != true || colattr.IsIdentity == true || colattr.IsPrimary == true) && colattr.DbType.Contains("NOT NULL") == false) + { + colattr.IsNullable = false; + colattr.DbType += " NOT NULL"; + } + if (colattr.IsNullable == true && colattr.DbType.Contains("NOT NULL")) colattr.DbType = colattr.DbType.Replace("NOT NULL", ""); + colattr.DbType = Regex.Replace(colattr.DbType, @"\([^\)]+\)", m => + { + var tmpLt = Regex.Replace(m.Groups[0].Value, @"\s", ""); + if (tmpLt.Contains("CHAR")) tmpLt = tmpLt.Replace("CHAR", " CHAR"); + if (tmpLt.Contains("BYTE")) tmpLt = tmpLt.Replace("BYTE", " BYTE"); + return tmpLt; + }); + if (colattr.IsIdentity == true && colattr.MapType.IsNumberType() == false) + colattr.IsIdentity = false; + if (setMethod == null) colattr.IsIgnore = true; - var col = new ColumnInfo { - Table = trytb, - CsName = p.Name, - CsType = p.PropertyType, - Attribute = colattr - }; - if (propsComment != null && propsComment.TryGetValue(p.Name, out var trycomment)) - col.Comment = trycomment; - if (colattr.IsIgnore) { - trytb.ColumnsByCsIgnore.Add(p.Name, col); - continue; - } - colattr.DbDefautValue = trytb.Properties[p.Name].GetValue(Activator.CreateInstance(trytb.Type)); - if (colattr.DbDefautValue != null && p.PropertyType != colattr.MapType) colattr.DbDefautValue = Utils.GetDataReaderValue(colattr.MapType, colattr.DbDefautValue); - if (colattr.DbDefautValue == null) colattr.DbDefautValue = tp?.defaultValue; - if (colattr.IsNullable == false && colattr.DbDefautValue == null) { - var citype = colattr.MapType.IsNullableType() ? colattr.MapType.GenericTypeArguments.FirstOrDefault() : colattr.MapType; - if (citype.IsArray) - colattr.DbDefautValue = Array.CreateInstance(citype, 0); - else - colattr.DbDefautValue = Activator.CreateInstance(citype); - } + var col = new ColumnInfo + { + Table = trytb, + CsName = p.Name, + CsType = p.PropertyType, + Attribute = colattr + }; + if (propsComment != null && propsComment.TryGetValue(p.Name, out var trycomment)) + col.Comment = trycomment; + if (colattr.IsIgnore) + { + trytb.ColumnsByCsIgnore.Add(p.Name, col); + continue; + } + colattr.DbDefautValue = trytb.Properties[p.Name].GetValue(Activator.CreateInstance(trytb.Type)); + if (colattr.DbDefautValue != null && p.PropertyType != colattr.MapType) colattr.DbDefautValue = Utils.GetDataReaderValue(colattr.MapType, colattr.DbDefautValue); + if (colattr.DbDefautValue == null) colattr.DbDefautValue = tp?.defaultValue; + if (colattr.IsNullable == false && colattr.DbDefautValue == null) + { + var citype = colattr.MapType.IsNullableType() ? colattr.MapType.GenericTypeArguments.FirstOrDefault() : colattr.MapType; + if (citype.IsArray) + colattr.DbDefautValue = Array.CreateInstance(citype, 0); + else + colattr.DbDefautValue = Activator.CreateInstance(citype); + } - trytb.Columns.Add(colattr.Name, col); - trytb.ColumnsByCs.Add(p.Name, col); - } - trytb.VersionColumn = trytb.Columns.Values.Where(a => a.Attribute.IsVersion == true).LastOrDefault(); - if (trytb.VersionColumn != null) { - if (trytb.VersionColumn.Attribute.MapType.IsNullableType() || trytb.VersionColumn.Attribute.MapType.IsNumberType() == false) - throw new Exception($"属性{trytb.VersionColumn.CsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型,并且不可为 Nullable"); - } - trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray(); - if (trytb.Primarys.Any() == false) { - var identcol = trytb.Columns.Values.Where(a => a.Attribute.IsIdentity == true).FirstOrDefault(); - if (identcol != null) trytb.Primarys = new[] { identcol }; - if (trytb.Primarys.Any() == false) { - trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, "id", true) == 0).ToArray(); - if (trytb.Primarys.Any() == false) { - trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, $"{trytb.DbName}id", true) == 0).ToArray(); - if (trytb.Primarys.Any() == false) { - trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, $"{trytb.DbName}_id", true) == 0).ToArray(); - } - } - } - foreach (var col in trytb.Primarys) - col.Attribute.IsPrimary = true; - } - //从数据库查找主键、自增 - if (common.CodeFirst.IsConfigEntityFromDbFirst) { - try { - if (common._orm.DbFirst != null) { - if (common.dbTables == null) - lock (common.dbTablesLock) - if (common.dbTables == null) - common.dbTables = common._orm.DbFirst.GetTablesByDatabase(); + trytb.Columns.Add(colattr.Name, col); + trytb.ColumnsByCs.Add(p.Name, col); + } + trytb.VersionColumn = trytb.Columns.Values.Where(a => a.Attribute.IsVersion == true).LastOrDefault(); + if (trytb.VersionColumn != null) + { + if (trytb.VersionColumn.Attribute.MapType.IsNullableType() || trytb.VersionColumn.Attribute.MapType.IsNumberType() == false) + throw new Exception($"属性{trytb.VersionColumn.CsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型,并且不可为 Nullable"); + } + trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray(); + if (trytb.Primarys.Any() == false) + { + var identcol = trytb.Columns.Values.Where(a => a.Attribute.IsIdentity == true).FirstOrDefault(); + if (identcol != null) trytb.Primarys = new[] { identcol }; + if (trytb.Primarys.Any() == false) + { + trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, "id", true) == 0).ToArray(); + if (trytb.Primarys.Any() == false) + { + trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, $"{trytb.DbName}id", true) == 0).ToArray(); + if (trytb.Primarys.Any() == false) + { + trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, $"{trytb.DbName}_id", true) == 0).ToArray(); + } + } + } + foreach (var col in trytb.Primarys) + col.Attribute.IsPrimary = true; + } + //从数据库查找主键、自增 + if (common.CodeFirst.IsConfigEntityFromDbFirst) + { + try + { + if (common._orm.DbFirst != null) + { + if (common.dbTables == null) + lock (common.dbTablesLock) + if (common.dbTables == null) + common.dbTables = common._orm.DbFirst.GetTablesByDatabase(); - var finddbtbs = common.dbTables.Where(a => string.Compare(a.Name, trytb.CsName, true) == 0 || string.Compare(a.Name, trytb.DbName, true) == 0); - foreach (var dbtb in finddbtbs) { - foreach (var dbident in dbtb.Identitys) { - if (trytb.Columns.TryGetValue(dbident.Name, out var trycol) && trycol.Attribute.MapType == dbident.CsType || - trytb.ColumnsByCs.TryGetValue(dbident.Name, out trycol) && trycol.Attribute.MapType == dbident.CsType) { - trycol.Attribute.IsIdentity = true; - } - } - foreach (var dbpk in dbtb.Primarys) { - if (trytb.Columns.TryGetValue(dbpk.Name, out var trycol) && trycol.Attribute.MapType == dbpk.CsType || - trytb.ColumnsByCs.TryGetValue(dbpk.Name, out trycol) && trycol.Attribute.MapType == dbpk.CsType) { - trycol.Attribute.IsPrimary = true; - } - } - foreach(var dbuk in dbtb.UniquesDict) { - foreach (var dbcol in dbuk.Value) { - if (trytb.Columns.TryGetValue(dbcol.Name, out var trycol) && trycol.Attribute.MapType == dbcol.CsType || - trytb.ColumnsByCs.TryGetValue(dbcol.Name, out trycol) && trycol.Attribute.MapType == dbcol.CsType) { - if (trycol.Attribute._Uniques?.Contains(dbuk.Key) != true) - trycol.Attribute.Unique += $"," + dbuk.Key; - } - } - } - } - } - } catch { } - trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray(); - } - var allunique = trytb.Columns.Values.Where(a => a.Attribute._Uniques != null).SelectMany(a => a.Attribute._Uniques).Distinct(); - trytb.Uniques = allunique.ToDictionary(a => a, a => trytb.Columns.Values.Where(b => b.Attribute._Uniques != null && b.Attribute._Uniques.Contains(a)).ToList()); - tbc.AddOrUpdate(entity, trytb, (oldkey, oldval) => trytb); + var finddbtbs = common.dbTables.Where(a => string.Compare(a.Name, trytb.CsName, true) == 0 || string.Compare(a.Name, trytb.DbName, true) == 0); + foreach (var dbtb in finddbtbs) + { + foreach (var dbident in dbtb.Identitys) + { + if (trytb.Columns.TryGetValue(dbident.Name, out var trycol) && trycol.Attribute.MapType == dbident.CsType || + trytb.ColumnsByCs.TryGetValue(dbident.Name, out trycol) && trycol.Attribute.MapType == dbident.CsType) + { + trycol.Attribute.IsIdentity = true; + } + } + foreach (var dbpk in dbtb.Primarys) + { + if (trytb.Columns.TryGetValue(dbpk.Name, out var trycol) && trycol.Attribute.MapType == dbpk.CsType || + trytb.ColumnsByCs.TryGetValue(dbpk.Name, out trycol) && trycol.Attribute.MapType == dbpk.CsType) + { + trycol.Attribute.IsPrimary = true; + } + } + foreach (var dbuk in dbtb.UniquesDict) + { + foreach (var dbcol in dbuk.Value) + { + if (trytb.Columns.TryGetValue(dbcol.Name, out var trycol) && trycol.Attribute.MapType == dbcol.CsType || + trytb.ColumnsByCs.TryGetValue(dbcol.Name, out trycol) && trycol.Attribute.MapType == dbcol.CsType) + { + if (trycol.Attribute._Uniques?.Contains(dbuk.Key) != true) + trycol.Attribute.Unique += $"," + dbuk.Key; + } + } + } + } + } + } + catch { } + trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray(); + } + var allunique = trytb.Columns.Values.Where(a => a.Attribute._Uniques != null).SelectMany(a => a.Attribute._Uniques).Distinct(); + trytb.Uniques = allunique.ToDictionary(a => a, a => trytb.Columns.Values.Where(b => b.Attribute._Uniques != null && b.Attribute._Uniques.Contains(a)).ToList()); + tbc.AddOrUpdate(entity, trytb, (oldkey, oldval) => trytb); - #region 查找导航属性的关系、virtual 属性延时加载,动态产生新的重写类 - var trytbTypeName = trytb.Type.IsNested ? $"{trytb.Type.DeclaringType.Namespace}.{trytb.Type.DeclaringType.Name}.{trytb.Type.Name}" : $"{trytb.Type.Namespace}.{trytb.Type.Name}"; - var trytbTypeLazyName = default(string); - var overrieds = 0; - StringBuilder cscode = null; - if (common.CodeFirst.IsLazyLoading && propsLazy.Any()) { - if (trytb.Type.IsPublic == false && trytb.Type.IsNestedPublic == false) throw new Exception($"【延时加载】实体类型 {trytbTypeName} 必须声明为 public"); + #region 查找导航属性的关系、virtual 属性延时加载,动态产生新的重写类 + var trytbTypeName = trytb.Type.IsNested ? $"{trytb.Type.DeclaringType.Namespace}.{trytb.Type.DeclaringType.Name}.{trytb.Type.Name}" : $"{trytb.Type.Namespace}.{trytb.Type.Name}"; + var trytbTypeLazyName = default(string); + var overrieds = 0; + StringBuilder cscode = null; + if (common.CodeFirst.IsLazyLoading && propsLazy.Any()) + { + if (trytb.Type.IsPublic == false && trytb.Type.IsNestedPublic == false) throw new Exception($"【延时加载】实体类型 {trytbTypeName} 必须声明为 public"); - trytbTypeLazyName = $"FreeSqlLazyEntity__{Regex.Replace(trytbTypeName, @"[^\w\d]", "_")}"; - - cscode = new StringBuilder(); - cscode.AppendLine("using System;") - .AppendLine("using FreeSql.DataAnnotations;") - .AppendLine("using System.Collections.Generic;") - .AppendLine("using System.Linq;") - .AppendLine("using Newtonsoft.Json;") - .AppendLine() - .Append("public class ").Append(trytbTypeLazyName).Append(" : ").Append(trytbTypeName).AppendLine(" {") - .AppendLine(" [JsonIgnore] private IFreeSql __fsql_orm__ { get; set; }\r\n"); - } + trytbTypeLazyName = $"FreeSqlLazyEntity__{Regex.Replace(trytbTypeName, @"[^\w\d]", "_")}"; - foreach(var pnv in propsNavObjs) { - var vp = propsLazy.Where(a => a.Item1 == pnv).FirstOrDefault(); - var isLazy = vp.Item1 != null && !string.IsNullOrEmpty(trytbTypeLazyName); - var propTypeName = pnv.PropertyType.IsGenericType ? - $"{pnv.PropertyType.Namespace}.{pnv.PropertyType.Name.Remove(pnv.PropertyType.Name.IndexOf('`'))}<{string.Join(", ", pnv.PropertyType.GenericTypeArguments.Select(a => a.IsNested ? $"{a.DeclaringType.Namespace}.{a.DeclaringType.Name}.{a.Name}" : $"{a.Namespace}.{a.Name}"))}>" : - (pnv.PropertyType.IsNested ? $"{pnv.PropertyType.DeclaringType.Namespace}.{pnv.PropertyType.DeclaringType.Name}.{pnv.PropertyType.Name}" : $"{pnv.PropertyType.Namespace}.{pnv.PropertyType.Name}"); + cscode = new StringBuilder(); + cscode.AppendLine("using System;") + .AppendLine("using FreeSql.DataAnnotations;") + .AppendLine("using System.Collections.Generic;") + .AppendLine("using System.Linq;") + .AppendLine("using Newtonsoft.Json;") + .AppendLine() + .Append("public class ").Append(trytbTypeLazyName).Append(" : ").Append(trytbTypeName).AppendLine(" {") + .AppendLine(" [JsonIgnore] private IFreeSql __fsql_orm__ { get; set; }\r\n"); + } - var pnvBind = pnv.GetCustomAttribute()?.Bind.Split(',').Select(a => a.Trim()).Where(a => !string.IsNullOrEmpty(a)).ToArray(); - var nvref = new TableRef(); - nvref.Property = pnv; + foreach (var pnv in propsNavObjs) + { + var vp = propsLazy.Where(a => a.Item1 == pnv).FirstOrDefault(); + var isLazy = vp.Item1 != null && !string.IsNullOrEmpty(trytbTypeLazyName); + var propTypeName = pnv.PropertyType.IsGenericType ? + $"{pnv.PropertyType.Namespace}.{pnv.PropertyType.Name.Remove(pnv.PropertyType.Name.IndexOf('`'))}<{string.Join(", ", pnv.PropertyType.GenericTypeArguments.Select(a => a.IsNested ? $"{a.DeclaringType.Namespace}.{a.DeclaringType.Name}.{a.Name}" : $"{a.Namespace}.{a.Name}"))}>" : + (pnv.PropertyType.IsNested ? $"{pnv.PropertyType.DeclaringType.Namespace}.{pnv.PropertyType.DeclaringType.Name}.{pnv.PropertyType.Name}" : $"{pnv.PropertyType.Namespace}.{pnv.PropertyType.Name}"); - //List 或 ICollection,一对多、多对多 - var propElementType = pnv.PropertyType.GenericTypeArguments.FirstOrDefault() ?? pnv.PropertyType.GetElementType(); - if (propElementType != null) { - if (typeof(IEnumerable).IsAssignableFrom(pnv.PropertyType) == false) continue; - if (trytb.Primarys.Any() == false) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {trytbTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - continue; - } + var pnvBind = pnv.GetCustomAttribute()?.Bind.Split(',').Select(a => a.Trim()).Where(a => !string.IsNullOrEmpty(a)).ToArray(); + var nvref = new TableRef(); + nvref.Property = pnv; - var tbref = propElementType == trytb.Type ? trytb : GetTableByEntity(propElementType, common); //可能是父子关系 - if (tbref == null) continue; + //List 或 ICollection,一对多、多对多 + var propElementType = pnv.PropertyType.GenericTypeArguments.FirstOrDefault() ?? pnv.PropertyType.GetElementType(); + if (propElementType != null) + { + if (typeof(IEnumerable).IsAssignableFrom(pnv.PropertyType) == false) continue; + if (trytb.Primarys.Any() == false) + { + nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {trytbTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + continue; + } - var tbrefTypeName = tbref.Type.IsNested ? $"{tbref.Type.DeclaringType.Namespace}.{tbref.Type.DeclaringType.Name}.{tbref.Type.Name}" : $"{tbref.Type.Namespace}.{tbref.Type.Name}"; - Type midType = null; - var isManyToMany = propElementType != trytb.Type && - pnv.Name.EndsWith($"{tbref.CsName}s") && - tbref.Properties.Where(z => (z.Value.PropertyType.GenericTypeArguments.FirstOrDefault() == trytb.Type || z.Value.PropertyType.GetElementType() == trytb.Type) && - z.Key.EndsWith($"{trytb.CsName}s", StringComparison.CurrentCultureIgnoreCase) && - typeof(IEnumerable).IsAssignableFrom(z.Value.PropertyType)).Any(); - if (isManyToMany) { - if (tbref.Primarys.Any() == false) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {tbrefTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - continue; - } + var tbref = propElementType == trytb.Type ? trytb : GetTableByEntity(propElementType, common); //可能是父子关系 + if (tbref == null) continue; - //中间表怎么查询,比如 Song、Tag、SongTag - var midFlagStr = pnv.Name.Remove(pnv.Name.Length - tbref.CsName.Length - 1); + var tbrefTypeName = tbref.Type.IsNested ? $"{tbref.Type.DeclaringType.Namespace}.{tbref.Type.DeclaringType.Name}.{tbref.Type.Name}" : $"{tbref.Type.Namespace}.{tbref.Type.Name}"; + Type midType = null; + var isManyToMany = propElementType != trytb.Type && + pnv.Name.EndsWith($"{tbref.CsName}s") && + tbref.Properties.Where(z => (z.Value.PropertyType.GenericTypeArguments.FirstOrDefault() == trytb.Type || z.Value.PropertyType.GetElementType() == trytb.Type) && + z.Key.EndsWith($"{trytb.CsName}s", StringComparison.CurrentCultureIgnoreCase) && + typeof(IEnumerable).IsAssignableFrom(z.Value.PropertyType)).Any(); + if (isManyToMany) + { + if (tbref.Primarys.Any() == false) + { + nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {tbrefTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + continue; + } - #region 在 trytb 命名空间下查找中间类 - midType = trytb.Type.IsNested ? - trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.Type.DeclaringType.Name}+{trytb.CsName}{tbref.CsName}{midFlagStr}", false, true) : //SongTag - trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.CsName}{tbref.CsName}{midFlagStr}", false, true); - if (midType != null) { - var midTypeProps = midType.GetProperties(); - var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); - var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); - if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; - } - if (midType == null) { - midType = trytb.Type.IsNested ? - trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.Type.DeclaringType.Name}+{trytb.CsName}_{tbref.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true) : //Song_Tag - trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.CsName}_{tbref.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true); - if (midType != null) { - var midTypeProps = midType.GetProperties(); - var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); - var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); - if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; - } - } - if (midType == null) { - midType = trytb.Type.IsNested ? - trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.Type.DeclaringType.Name}+{tbref.CsName}{trytb.CsName}{midFlagStr}", false, true) : //TagSong - trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{tbref.CsName}{trytb.CsName}{midFlagStr}", false, true); - if (midType != null) { - var midTypeProps = midType.GetProperties(); - var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); - var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); - if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; - } - } - if (midType == null) { - midType = trytb.Type.IsNested ? - trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.Type.DeclaringType.Name}+{tbref.CsName}_{trytb.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true) : //Tag_Song - trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{tbref.CsName}_{trytb.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true); - if (midType != null) { - var midTypeProps = midType.GetProperties(); - var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); - var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); - if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; - } - } - #endregion + //中间表怎么查询,比如 Song、Tag、SongTag + var midFlagStr = pnv.Name.Remove(pnv.Name.Length - tbref.CsName.Length - 1); - #region 在 tbref 命名空间下查找中间类 - if (midType == null) { - midType = tbref.Type.IsNested ? - tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.Type.DeclaringType.Name}+{trytb.CsName}{tbref.CsName}{midFlagStr}", false, true) : //SongTag - tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{trytb.CsName}{tbref.CsName}{midFlagStr}", false, true); - if (midType != null) { - var midTypeProps = midType.GetProperties(); - var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); - var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); - if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; - } - } - if (midType == null) { - midType = tbref.Type.IsNested ? - tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.Type.DeclaringType.Name}+{trytb.CsName}_{tbref.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true) : //Song_Tag - tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{trytb.CsName}_{tbref.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true); - if (midType != null) { - var midTypeProps = midType.GetProperties(); - var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); - var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); - if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; - } - } - if (midType == null) { - midType = tbref.Type.IsNested ? - tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.Type.DeclaringType.Name}+{tbref.CsName}{trytb.CsName}{midFlagStr}", false, true) : //TagSong - tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.CsName}{trytb.CsName}{midFlagStr}", false, true); - if (midType != null) { - var midTypeProps = midType.GetProperties(); - var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); - var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); - if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; - } - } - if (midType == null) { - midType = tbref.Type.IsNested ? - tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.Type.DeclaringType.Name}+{tbref.CsName}_{trytb.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true) : //Tag_Song - tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.CsName}_{trytb.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true); - if (midType != null) { - var midTypeProps = midType.GetProperties(); - var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); - var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); - if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; - } - } - #endregion + #region 在 trytb 命名空间下查找中间类 + midType = trytb.Type.IsNested ? + trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.Type.DeclaringType.Name}+{trytb.CsName}{tbref.CsName}{midFlagStr}", false, true) : //SongTag + trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.CsName}{tbref.CsName}{midFlagStr}", false, true); + if (midType != null) + { + var midTypeProps = midType.GetProperties(); + var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); + var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); + if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; + } + if (midType == null) + { + midType = trytb.Type.IsNested ? + trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.Type.DeclaringType.Name}+{trytb.CsName}_{tbref.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true) : //Song_Tag + trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.CsName}_{tbref.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true); + if (midType != null) + { + var midTypeProps = midType.GetProperties(); + var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); + var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); + if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; + } + } + if (midType == null) + { + midType = trytb.Type.IsNested ? + trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.Type.DeclaringType.Name}+{tbref.CsName}{trytb.CsName}{midFlagStr}", false, true) : //TagSong + trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{tbref.CsName}{trytb.CsName}{midFlagStr}", false, true); + if (midType != null) + { + var midTypeProps = midType.GetProperties(); + var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); + var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); + if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; + } + } + if (midType == null) + { + midType = trytb.Type.IsNested ? + trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{trytb.Type.DeclaringType.Name}+{tbref.CsName}_{trytb.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true) : //Tag_Song + trytb.Type.Assembly.GetType($"{trytb.Type.Namespace}.{tbref.CsName}_{trytb.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true); + if (midType != null) + { + var midTypeProps = midType.GetProperties(); + var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); + var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); + if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; + } + } + #endregion - isManyToMany = midType != null; - } - if (isManyToMany) { - var tbmid = GetTableByEntity(midType, common); - var midTypePropsTrytb = tbmid.Properties.Where(a => a.Value.PropertyType == trytb.Type).FirstOrDefault().Value; - //g.mysql.Select().Where(a => g.mysql.Select().Where(b => b.Tag_id == a.Id && b.Song_id == 1).Any()); - var lmbdWhere = isLazy ? new StringBuilder() : null; - for (var a = 0; a < trytb.Primarys.Length; a++) { - var findtrytbPkCsName = trytb.Primarys[a].CsName.TrimStart('_'); - if (findtrytbPkCsName.StartsWith(trytb.Type.Name, StringComparison.CurrentCultureIgnoreCase)) findtrytbPkCsName = findtrytbPkCsName.Substring(trytb.Type.Name.Length).TrimStart('_'); - if (tbmid.ColumnsByCs.TryGetValue($"{midTypePropsTrytb.Name}{findtrytbPkCsName}", out var trycol) == false && //骆峰命名 - tbmid.ColumnsByCs.TryGetValue($"{midTypePropsTrytb.Name}_{findtrytbPkCsName}", out trycol) == false //下划线命名 - ) { + #region 在 tbref 命名空间下查找中间类 + if (midType == null) + { + midType = tbref.Type.IsNested ? + tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.Type.DeclaringType.Name}+{trytb.CsName}{tbref.CsName}{midFlagStr}", false, true) : //SongTag + tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{trytb.CsName}{tbref.CsName}{midFlagStr}", false, true); + if (midType != null) + { + var midTypeProps = midType.GetProperties(); + var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); + var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); + if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; + } + } + if (midType == null) + { + midType = tbref.Type.IsNested ? + tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.Type.DeclaringType.Name}+{trytb.CsName}_{tbref.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true) : //Song_Tag + tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{trytb.CsName}_{tbref.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true); + if (midType != null) + { + var midTypeProps = midType.GetProperties(); + var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); + var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); + if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; + } + } + if (midType == null) + { + midType = tbref.Type.IsNested ? + tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.Type.DeclaringType.Name}+{tbref.CsName}{trytb.CsName}{midFlagStr}", false, true) : //TagSong + tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.CsName}{trytb.CsName}{midFlagStr}", false, true); + if (midType != null) + { + var midTypeProps = midType.GetProperties(); + var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); + var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); + if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; + } + } + if (midType == null) + { + midType = tbref.Type.IsNested ? + tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.Type.DeclaringType.Name}+{tbref.CsName}_{trytb.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true) : //Tag_Song + tbref.Type.Assembly.GetType($"{tbref.Type.Namespace}.{tbref.CsName}_{trytb.CsName}{(string.IsNullOrEmpty(midFlagStr) ? "" : "_")}{midFlagStr}", false, true); + if (midType != null) + { + var midTypeProps = midType.GetProperties(); + var midTypePropsTrytb = midTypeProps.Where(a => a.PropertyType == trytb.Type).Count(); + var midTypePropsTbref = midTypeProps.Where(a => a.PropertyType == tbref.Type).Count(); + if (midTypePropsTrytb != 1 || midTypePropsTbref != 1) midType = null; + } + } + #endregion - } - if (trycol != null && trycol.CsType.NullableTypeOrThis() != trytb.Primarys[a].CsType) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{tbmid.CsName}.{trycol.CsName} 和 {trytb.CsName}.{trytb.Primarys[a].CsName} 类型不一致"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } - if (trycol == null) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbmid.CsName} 中没有找到对应的字段,如:{midTypePropsTrytb.Name}{findtrytbPkCsName}、{midTypePropsTrytb.Name}_{findtrytbPkCsName}"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } + isManyToMany = midType != null; + } + if (isManyToMany) + { + var tbmid = GetTableByEntity(midType, common); + var midTypePropsTrytb = tbmid.Properties.Where(a => a.Value.PropertyType == trytb.Type).FirstOrDefault().Value; + //g.mysql.Select().Where(a => g.mysql.Select().Where(b => b.Tag_id == a.Id && b.Song_id == 1).Any()); + var lmbdWhere = isLazy ? new StringBuilder() : null; + for (var a = 0; a < trytb.Primarys.Length; a++) + { + var findtrytbPkCsName = trytb.Primarys[a].CsName.TrimStart('_'); + if (findtrytbPkCsName.StartsWith(trytb.Type.Name, StringComparison.CurrentCultureIgnoreCase)) findtrytbPkCsName = findtrytbPkCsName.Substring(trytb.Type.Name.Length).TrimStart('_'); + if (tbmid.ColumnsByCs.TryGetValue($"{midTypePropsTrytb.Name}{findtrytbPkCsName}", out var trycol) == false && //骆峰命名 + tbmid.ColumnsByCs.TryGetValue($"{midTypePropsTrytb.Name}_{findtrytbPkCsName}", out trycol) == false //下划线命名 + ) + { - nvref.Columns.Add(trytb.Primarys[a]); - nvref.MiddleColumns.Add(trycol); - if (tbmid.Primarys.Any() == false) - trycol.Attribute.IsPrimary = true; + } + if (trycol != null && trycol.CsType.NullableTypeOrThis() != trytb.Primarys[a].CsType) + { + nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{tbmid.CsName}.{trycol.CsName} 和 {trytb.CsName}.{trytb.Primarys[a].CsName} 类型不一致"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } + if (trycol == null) + { + nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbmid.CsName} 中没有找到对应的字段,如:{midTypePropsTrytb.Name}{findtrytbPkCsName}、{midTypePropsTrytb.Name}_{findtrytbPkCsName}"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } - if (isLazy) { - if (a > 0) lmbdWhere.Append(" && "); - lmbdWhere.Append("b.").Append(trycol.CsName).Append(" == this.").Append(trytb.Primarys[a].CsName); - } - } + nvref.Columns.Add(trytb.Primarys[a]); + nvref.MiddleColumns.Add(trycol); + if (tbmid.Primarys.Any() == false) + trycol.Attribute.IsPrimary = true; - if (nvref.Exception == null) { - var midTypePropsTbref = tbmid.Properties.Where(a => a.Value.PropertyType == tbref.Type).FirstOrDefault().Value; - for (var a = 0; a < tbref.Primarys.Length; a++) { - var findtbrefPkCsName = tbref.Primarys[a].CsName.TrimStart('_'); - if (findtbrefPkCsName.StartsWith(tbref.Type.Name, StringComparison.CurrentCultureIgnoreCase)) findtbrefPkCsName = findtbrefPkCsName.Substring(tbref.Type.Name.Length).TrimStart('_'); - if (tbmid.ColumnsByCs.TryGetValue($"{midTypePropsTbref.Name}{findtbrefPkCsName}", out var trycol) == false && //骆峰命名 - tbmid.ColumnsByCs.TryGetValue($"{midTypePropsTbref.Name}_{findtbrefPkCsName}", out trycol) == false //下划线命名 - ) { + if (isLazy) + { + if (a > 0) lmbdWhere.Append(" && "); + lmbdWhere.Append("b.").Append(trycol.CsName).Append(" == this.").Append(trytb.Primarys[a].CsName); + } + } - } - if (trycol != null && trycol.CsType.NullableTypeOrThis() != tbref.Primarys[a].CsType) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{tbmid.CsName}.{trycol.CsName} 和 {tbref.CsName}.{tbref.Primarys[a].CsName} 类型不一致"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } - if (trycol == null) { - nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbmid.CsName} 中没有找到对应的字段,如:{midTypePropsTbref.Name}{findtbrefPkCsName}、{midTypePropsTbref.Name}_{findtbrefPkCsName}"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } + if (nvref.Exception == null) + { + var midTypePropsTbref = tbmid.Properties.Where(a => a.Value.PropertyType == tbref.Type).FirstOrDefault().Value; + for (var a = 0; a < tbref.Primarys.Length; a++) + { + var findtbrefPkCsName = tbref.Primarys[a].CsName.TrimStart('_'); + if (findtbrefPkCsName.StartsWith(tbref.Type.Name, StringComparison.CurrentCultureIgnoreCase)) findtbrefPkCsName = findtbrefPkCsName.Substring(tbref.Type.Name.Length).TrimStart('_'); + if (tbmid.ColumnsByCs.TryGetValue($"{midTypePropsTbref.Name}{findtbrefPkCsName}", out var trycol) == false && //骆峰命名 + tbmid.ColumnsByCs.TryGetValue($"{midTypePropsTbref.Name}_{findtbrefPkCsName}", out trycol) == false //下划线命名 + ) + { - nvref.RefColumns.Add(tbref.Primarys[a]); - nvref.MiddleColumns.Add(trycol); - if (tbmid.Primarys.Any() == false) - trycol.Attribute.IsPrimary = true; + } + if (trycol != null && trycol.CsType.NullableTypeOrThis() != tbref.Primarys[a].CsType) + { + nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{tbmid.CsName}.{trycol.CsName} 和 {tbref.CsName}.{tbref.Primarys[a].CsName} 类型不一致"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } + if (trycol == null) + { + nvref.Exception = new Exception($"【ManyToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbmid.CsName} 中没有找到对应的字段,如:{midTypePropsTbref.Name}{findtbrefPkCsName}、{midTypePropsTbref.Name}_{findtbrefPkCsName}"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } - if (isLazy) lmbdWhere.Append(" && b.").Append(trycol.CsName).Append(" == a.").Append(tbref.Primarys[a].CsName); - } - } - if (nvref.Columns.Count > 0 && nvref.RefColumns.Count > 0) { - nvref.RefMiddleEntityType = tbmid.Type; - nvref.RefEntityType = tbref.Type; - nvref.RefType = TableRefType.ManyToMany; - trytb.AddOrUpdateTableRef(pnv.Name, nvref); + nvref.RefColumns.Add(tbref.Primarys[a]); + nvref.MiddleColumns.Add(trycol); + if (tbmid.Primarys.Any() == false) + trycol.Attribute.IsPrimary = true; - if (tbmid.Primarys.Any() == false) - tbmid.Primarys = tbmid.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray(); - } + if (isLazy) lmbdWhere.Append(" && b.").Append(trycol.CsName).Append(" == a.").Append(tbref.Primarys[a].CsName); + } + } + if (nvref.Columns.Count > 0 && nvref.RefColumns.Count > 0) + { + nvref.RefMiddleEntityType = tbmid.Type; + nvref.RefEntityType = tbref.Type; + nvref.RefType = TableRefType.ManyToMany; + trytb.AddOrUpdateTableRef(pnv.Name, nvref); - if (isLazy) { - cscode.Append(" private bool __lazy__").Append(pnv.Name).AppendLine(" = false;") - .Append(" public override ").Append(propTypeName).Append(" ").Append(pnv.Name).AppendLine(" {"); - if (vp.Item2) { //get 重写 - cscode.Append(" get {\r\n") - .Append(" if (base.").Append(pnv.Name).Append(" == null && __lazy__").Append(pnv.Name).AppendLine(" == false) {"); + if (tbmid.Primarys.Any() == false) + tbmid.Primarys = tbmid.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray(); + } - if (nvref.Exception == null) - cscode.Append(" base.").Append(pnv.Name).Append(" = __fsql_orm__.Select<").Append(propElementType.IsNested ? $"{propElementType.DeclaringType.Namespace}.{propElementType.DeclaringType.Name}.{propElementType.Name}" : $"{propElementType.Namespace}.{propElementType.Name}") - .Append(">().Where(a => __fsql_orm__.Select<").Append(tbmid.Type.IsNested ? $"{tbmid.Type.DeclaringType.Namespace}.{tbmid.Type.DeclaringType.Name}.{tbmid.Type.Name}" : $"{tbmid.Type.Namespace}.{tbmid.Type.Name}") - .Append(">().Where(b => ").Append(lmbdWhere.ToString()).AppendLine(").Any()).ToList();") - .Append(" __lazy__").Append(pnv.Name).AppendLine(" = true;"); - else - cscode.Append(" throw new Exception(\"").Append(nvref.Exception.Message.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")).AppendLine("\");"); + if (isLazy) + { + cscode.Append(" private bool __lazy__").Append(pnv.Name).AppendLine(" = false;") + .Append(" public override ").Append(propTypeName).Append(" ").Append(pnv.Name).AppendLine(" {"); + if (vp.Item2) + { //get 重写 + cscode.Append(" get {\r\n") + .Append(" if (base.").Append(pnv.Name).Append(" == null && __lazy__").Append(pnv.Name).AppendLine(" == false) {"); - cscode.Append(" }\r\n") - .Append(" return base.").Append(pnv.Name).AppendLine(";") - .Append(" }\r\n"); - } - if (vp.Item3) { //set 重写 - cscode.Append(" set => base.").Append(pnv.Name).AppendLine(" = value;"); - } - cscode.AppendLine(" }"); - } - } else { //One To Many - List bindColumns = new List(); - if (pnvBind != null) { - foreach(var bi in pnvBind) { - if (tbref.ColumnsByCs.TryGetValue(bi, out var trybindcol) == false) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi}"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } - bindColumns.Add(trybindcol); - } - } + if (nvref.Exception == null) + cscode.Append(" base.").Append(pnv.Name).Append(" = __fsql_orm__.Select<").Append(propElementType.IsNested ? $"{propElementType.DeclaringType.Namespace}.{propElementType.DeclaringType.Name}.{propElementType.Name}" : $"{propElementType.Namespace}.{propElementType.Name}") + .Append(">().Where(a => __fsql_orm__.Select<").Append(tbmid.Type.IsNested ? $"{tbmid.Type.DeclaringType.Namespace}.{tbmid.Type.DeclaringType.Name}.{tbmid.Type.Name}" : $"{tbmid.Type.Namespace}.{tbmid.Type.Name}") + .Append(">().Where(b => ").Append(lmbdWhere.ToString()).AppendLine(").Any()).ToList();") + .Append(" __lazy__").Append(pnv.Name).AppendLine(" = true;"); + else + cscode.Append(" throw new Exception(\"").Append(nvref.Exception.Message.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")).AppendLine("\");"); - PropertyInfo refprop = null; - var refcols = tbref.Properties.Where(z => z.Value.PropertyType == trytb.Type); - refprop = refcols.Count() == 1 ? refcols.First().Value : null; - var lmbdWhere = isLazy ? new StringBuilder() : null; + cscode.Append(" }\r\n") + .Append(" return base.").Append(pnv.Name).AppendLine(";") + .Append(" }\r\n"); + } + if (vp.Item3) + { //set 重写 + cscode.Append(" set => base.").Append(pnv.Name).AppendLine(" = value;"); + } + cscode.AppendLine(" }"); + } + } + else + { //One To Many + List bindColumns = new List(); + if (pnvBind != null) + { + foreach (var bi in pnvBind) + { + if (tbref.ColumnsByCs.TryGetValue(bi, out var trybindcol) == false) + { + nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] 解析错误,在 {tbrefTypeName} 未找到属性:{bi}"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } + bindColumns.Add(trybindcol); + } + } - if (nvref.Exception == null && bindColumns.Any() && bindColumns.Count != trytb.Primarys.Length) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] Bind 数目({bindColumns.Count}) 与 内部主键数目({trytb.Primarys.Length}) 不相同"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - } - for (var a = 0; nvref.Exception == null && a < trytb.Primarys.Length; a++) { - var findtrytbPkCsName = trytb.Primarys[a].CsName.TrimStart('_'); - if (findtrytbPkCsName.StartsWith(trytb.Type.Name, StringComparison.CurrentCultureIgnoreCase)) findtrytbPkCsName = findtrytbPkCsName.Substring(trytb.Type.Name.Length).TrimStart('_'); - var findtrytb = pnv.Name; - if (findtrytb.EndsWith(tbref.CsName + "s")) findtrytb = findtrytb.Substring(0, findtrytb.Length - tbref.CsName.Length - 1); - findtrytb += trytb.CsName; + PropertyInfo refprop = null; + var refcols = tbref.Properties.Where(z => z.Value.PropertyType == trytb.Type); + refprop = refcols.Count() == 1 ? refcols.First().Value : null; + var lmbdWhere = isLazy ? new StringBuilder() : null; - var trycol = bindColumns.Any() ? bindColumns[a] : null; - if (trycol == null && - tbref.ColumnsByCs.TryGetValue($"{findtrytb}{findtrytbPkCsName}", out trycol) == false && //骆峰命名 - tbref.ColumnsByCs.TryGetValue($"{findtrytb}_{findtrytbPkCsName}", out trycol) == false //下划线命名 - ) { - if (refprop != null && - tbref.ColumnsByCs.TryGetValue($"{refprop.Name}{findtrytbPkCsName}", out trycol) == false && //骆峰命名 - tbref.ColumnsByCs.TryGetValue($"{refprop.Name}_{findtrytbPkCsName}", out trycol) == false) //下划线命名 - { + if (nvref.Exception == null && bindColumns.Any() && bindColumns.Count != trytb.Primarys.Length) + { + nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] Bind 数目({bindColumns.Count}) 与 内部主键数目({trytb.Primarys.Length}) 不相同"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + } + for (var a = 0; nvref.Exception == null && a < trytb.Primarys.Length; a++) + { + var findtrytbPkCsName = trytb.Primarys[a].CsName.TrimStart('_'); + if (findtrytbPkCsName.StartsWith(trytb.Type.Name, StringComparison.CurrentCultureIgnoreCase)) findtrytbPkCsName = findtrytbPkCsName.Substring(trytb.Type.Name.Length).TrimStart('_'); + var findtrytb = pnv.Name; + if (findtrytb.EndsWith(tbref.CsName + "s")) findtrytb = findtrytb.Substring(0, findtrytb.Length - tbref.CsName.Length - 1); + findtrytb += trytb.CsName; - } - } - if (trycol != null && trycol.CsType.NullableTypeOrThis() != trytb.Primarys[a].CsType) { - nvref.Exception = new Exception($"【OneToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{trytb.CsName}.{trytb.Primarys[a].CsName} 和 {tbref.CsName}.{trycol.CsName} 类型不一致"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } - if (trycol == null) { - nvref.Exception = new Exception($"【OneToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbref.CsName} 中没有找到对应的字段,如:{findtrytb}{findtrytbPkCsName}、{findtrytb}_{findtrytbPkCsName}" + (refprop == null ? "" : $"、{refprop.Name}{findtrytbPkCsName}、{refprop.Name}_{findtrytbPkCsName}。或者使用 [Navigate] 特性指定关系映射。")); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } + var trycol = bindColumns.Any() ? bindColumns[a] : null; + if (trycol == null && + tbref.ColumnsByCs.TryGetValue($"{findtrytb}{findtrytbPkCsName}", out trycol) == false && //骆峰命名 + tbref.ColumnsByCs.TryGetValue($"{findtrytb}_{findtrytbPkCsName}", out trycol) == false //下划线命名 + ) + { + if (refprop != null && + tbref.ColumnsByCs.TryGetValue($"{refprop.Name}{findtrytbPkCsName}", out trycol) == false && //骆峰命名 + tbref.ColumnsByCs.TryGetValue($"{refprop.Name}_{findtrytbPkCsName}", out trycol) == false) //下划线命名 + { - nvref.Columns.Add(trytb.Primarys[a]); - nvref.RefColumns.Add(trycol); + } + } + if (trycol != null && trycol.CsType.NullableTypeOrThis() != trytb.Primarys[a].CsType) + { + nvref.Exception = new Exception($"【OneToMany】导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{trytb.CsName}.{trytb.Primarys[a].CsName} 和 {tbref.CsName}.{trycol.CsName} 类型不一致"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } + if (trycol == null) + { + nvref.Exception = new Exception($"【OneToMany】导航属性 {trytbTypeName}.{pnv.Name} 在 {tbref.CsName} 中没有找到对应的字段,如:{findtrytb}{findtrytbPkCsName}、{findtrytb}_{findtrytbPkCsName}" + (refprop == null ? "" : $"、{refprop.Name}{findtrytbPkCsName}、{refprop.Name}_{findtrytbPkCsName}。或者使用 [Navigate] 特性指定关系映射。")); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } - if (isLazy && nvref.Exception == null) { - if (a > 0) lmbdWhere.Append(" && "); - lmbdWhere.Append("a.").Append(trycol.CsName).Append(" == this.").Append(trytb.Primarys[a].CsName); + nvref.Columns.Add(trytb.Primarys[a]); + nvref.RefColumns.Add(trycol); - if (refprop == null) { //加载成功后,把列表对应的导航属性值设置为 this,比如 Select().ToOne().Topics 下的 TopicType 属性值全部为 this - var findtrytbName = trycol.CsName; - if (findtrytbName.EndsWith(trytb.Primarys.First().CsName)) { - findtrytbName = findtrytbName.Remove(findtrytbName.Length - trytb.Primarys.First().CsName.Length).TrimEnd('_'); - if (tbref.Properties.TryGetValue(findtrytbName, out refprop) && refprop.PropertyType != trytb.Type) - refprop = null; - } - } - } - } - if (nvref.Columns.Count > 0 && nvref.RefColumns.Count > 0) { - nvref.RefEntityType = tbref.Type; - nvref.RefType = TableRefType.OneToMany; - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - } + if (isLazy && nvref.Exception == null) + { + if (a > 0) lmbdWhere.Append(" && "); + lmbdWhere.Append("a.").Append(trycol.CsName).Append(" == this.").Append(trytb.Primarys[a].CsName); - if (isLazy) { - cscode.Append(" private bool __lazy__").Append(pnv.Name).AppendLine(" = false;") - .Append(" public override ").Append(propTypeName).Append(" ").Append(pnv.Name).AppendLine(" {"); - if (vp.Item2) { //get 重写 - cscode.Append(" get {\r\n") - .Append(" if (base.").Append(pnv.Name).Append(" == null && __lazy__").Append(pnv.Name).AppendLine(" == false) {"); + if (refprop == null) + { //加载成功后,把列表对应的导航属性值设置为 this,比如 Select().ToOne().Topics 下的 TopicType 属性值全部为 this + var findtrytbName = trycol.CsName; + if (findtrytbName.EndsWith(trytb.Primarys.First().CsName)) + { + findtrytbName = findtrytbName.Remove(findtrytbName.Length - trytb.Primarys.First().CsName.Length).TrimEnd('_'); + if (tbref.Properties.TryGetValue(findtrytbName, out refprop) && refprop.PropertyType != trytb.Type) + refprop = null; + } + } + } + } + if (nvref.Columns.Count > 0 && nvref.RefColumns.Count > 0) + { + nvref.RefEntityType = tbref.Type; + nvref.RefType = TableRefType.OneToMany; + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + } - if (nvref.Exception == null) { - cscode.Append(" base.").Append(pnv.Name).Append(" = __fsql_orm__.Select<").Append(propElementType.IsNested ? $"{propElementType.DeclaringType.Namespace}.{propElementType.DeclaringType.Name}.{propElementType.Name}" : $"{propElementType.Namespace}.{propElementType.Name}").Append(">().Where(a => ").Append(lmbdWhere.ToString()).AppendLine(").ToList();"); - if (refprop != null) { - cscode.Append(" foreach (var loc1 in base.").Append(pnv.Name).AppendLine(")") - .Append(" loc1.").Append(refprop.Name).AppendLine(" = this;") - .Append(" __lazy__").Append(pnv.Name).AppendLine(" = true;"); - } - } else - cscode.Append(" throw new Exception(\"").Append(nvref.Exception.Message.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")).AppendLine("\");"); + if (isLazy) + { + cscode.Append(" private bool __lazy__").Append(pnv.Name).AppendLine(" = false;") + .Append(" public override ").Append(propTypeName).Append(" ").Append(pnv.Name).AppendLine(" {"); + if (vp.Item2) + { //get 重写 + cscode.Append(" get {\r\n") + .Append(" if (base.").Append(pnv.Name).Append(" == null && __lazy__").Append(pnv.Name).AppendLine(" == false) {"); - cscode - .Append(" }\r\n") - .Append(" return base.").Append(pnv.Name).AppendLine(";") - .Append(" }\r\n"); - } - if (vp.Item3) { //set 重写 - cscode.Append(" set => base.").Append(pnv.Name).AppendLine(" = value;"); - } - cscode.AppendLine(" }"); - } - } - } else { //一对一、多对一 - var tbref = pnv.PropertyType == trytb.Type ? trytb : GetTableByEntity(pnv.PropertyType, common); //可能是父子关系 - if (tbref == null) continue; - if (tbref.Primarys.Any() == false) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {propTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - } - var tbrefTypeName = tbref.Type.IsNested ? $"{tbref.Type.DeclaringType.Namespace}.{tbref.Type.DeclaringType.Name}.{tbref.Type.Name}" : $"{tbref.Type.Namespace}.{tbref.Type.Name}"; - var isOnoToOne = pnv.PropertyType != trytb.Type && - tbref.Properties.Where(z => z.Value.PropertyType == trytb.Type).Any() && - tbref.Primarys.Length == trytb.Primarys.Length && - string.Join(",", tbref.Primarys.Select(a => a.CsType.FullName).OrderBy(a => a)) == string.Join(",", trytb.Primarys.Select(a => a.CsType.FullName).OrderBy(a => a)); + if (nvref.Exception == null) + { + cscode.Append(" base.").Append(pnv.Name).Append(" = __fsql_orm__.Select<").Append(propElementType.IsNested ? $"{propElementType.DeclaringType.Namespace}.{propElementType.DeclaringType.Name}.{propElementType.Name}" : $"{propElementType.Namespace}.{propElementType.Name}").Append(">().Where(a => ").Append(lmbdWhere.ToString()).AppendLine(").ToList();"); + if (refprop != null) + { + cscode.Append(" foreach (var loc1 in base.").Append(pnv.Name).AppendLine(")") + .Append(" loc1.").Append(refprop.Name).AppendLine(" = this;") + .Append(" __lazy__").Append(pnv.Name).AppendLine(" = true;"); + } + } + else + cscode.Append(" throw new Exception(\"").Append(nvref.Exception.Message.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")).AppendLine("\");"); - List bindColumns = new List(); - if (pnvBind != null) { - foreach(var bi in pnvBind) { - if (trytb.ColumnsByCs.TryGetValue(bi, out var trybindcol) == false) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] 解析错误,在 {trytbTypeName} 未找到属性:{bi}"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } - bindColumns.Add(trybindcol); - } - } - var lmbdWhere = new StringBuilder(); + cscode + .Append(" }\r\n") + .Append(" return base.").Append(pnv.Name).AppendLine(";") + .Append(" }\r\n"); + } + if (vp.Item3) + { //set 重写 + cscode.Append(" set => base.").Append(pnv.Name).AppendLine(" = value;"); + } + cscode.AppendLine(" }"); + } + } + } + else + { //一对一、多对一 + var tbref = pnv.PropertyType == trytb.Type ? trytb : GetTableByEntity(pnv.PropertyType, common); //可能是父子关系 + if (tbref == null) continue; + if (tbref.Primarys.Any() == false) + { + nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,实体类型 {propTypeName} 缺少主键标识,[Column(IsPrimary = true)]"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + } + var tbrefTypeName = tbref.Type.IsNested ? $"{tbref.Type.DeclaringType.Namespace}.{tbref.Type.DeclaringType.Name}.{tbref.Type.Name}" : $"{tbref.Type.Namespace}.{tbref.Type.Name}"; + var isOnoToOne = pnv.PropertyType != trytb.Type && + tbref.Properties.Where(z => z.Value.PropertyType == trytb.Type).Any() && + tbref.Primarys.Length == trytb.Primarys.Length && + string.Join(",", tbref.Primarys.Select(a => a.CsType.FullName).OrderBy(a => a)) == string.Join(",", trytb.Primarys.Select(a => a.CsType.FullName).OrderBy(a => a)); - if (nvref.Exception == null && bindColumns.Any() && bindColumns.Count != tbref.Primarys.Length) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] Bind 数目({bindColumns.Count}) 与 外部主键数目({tbref.Primarys.Length}) 不相同"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - } - for (var a = 0; nvref.Exception == null && a < tbref.Primarys.Length; a++) { - var findtbrefPkCsName = tbref.Primarys[a].CsName.TrimStart('_'); - if (findtbrefPkCsName.StartsWith(tbref.Type.Name, StringComparison.CurrentCultureIgnoreCase)) findtbrefPkCsName = findtbrefPkCsName.Substring(tbref.Type.Name.Length).TrimStart('_'); + List bindColumns = new List(); + if (pnvBind != null) + { + foreach (var bi in pnvBind) + { + if (trytb.ColumnsByCs.TryGetValue(bi, out var trybindcol) == false) + { + nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] 解析错误,在 {trytbTypeName} 未找到属性:{bi}"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } + bindColumns.Add(trybindcol); + } + } + var lmbdWhere = new StringBuilder(); - var trycol = bindColumns.Any() ? bindColumns[a] : null; - if (trycol == null && - trytb.ColumnsByCs.TryGetValue($"{pnv.Name}{findtbrefPkCsName}", out trycol) == false && //骆峰命名 - trytb.ColumnsByCs.TryGetValue($"{pnv.Name}_{findtbrefPkCsName}", out trycol) == false && //下划线命名 - //tbref.Primarys.Length == 1 && - trytb.ColumnsByCs.TryGetValue($"{pnv.Name}_Id", out trycol) == false && - trytb.ColumnsByCs.TryGetValue($"{pnv.Name}Id", out trycol) == false - ) { - //一对一,主键与主键查找 - if (isOnoToOne) { - var trytbpks = trytb.Primarys.Where(z => z.CsType == tbref.Primarys[a].CsType); //一对一,按类型 - if (trytbpks.Count() == 1) trycol = trytbpks.First(); - else { - trytbpks = trytb.Primarys.Where(z => string.Compare(z.CsName, tbref.Primarys[a].CsName, true) == 0); //一对一,按主键名相同 - if (trytbpks.Count() == 1) trycol = trytbpks.First(); - else { - trytbpks = trytb.Primarys.Where(z => string.Compare(z.CsName, $"{tbref.CsName}{tbref.Primarys[a].CsName}", true) == 0); //一对一,主键名 = 表+主键名 - if (trytbpks.Count() == 1) trycol = trytbpks.First(); - else { - trytbpks = trytb.Primarys.Where(z => string.Compare(z.CsName, $"{tbref.CsName}_{tbref.Primarys[a].CsName}", true) == 0); //一对一,主键名 = 表+_主键名 - if (trytbpks.Count() == 1) trycol = trytbpks.First(); - } - } - } - } - } - if (trycol != null && trycol.CsType.NullableTypeOrThis() != tbref.Primarys[a].CsType) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{trytb.CsName}.{trycol.CsName} 和 {tbref.CsName}.{tbref.Primarys[a].CsName} 类型不一致"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } - if (trycol == null) { - nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 没有找到对应的字段,如:{pnv.Name}{findtbrefPkCsName}、{pnv.Name}_{findtbrefPkCsName}。或者使用 [Navigate] 特性指定关系映射。"); - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - //if (isLazy) throw nvref.Exception; - break; - } + if (nvref.Exception == null && bindColumns.Any() && bindColumns.Count != tbref.Primarys.Length) + { + nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 特性 [Navigate] Bind 数目({bindColumns.Count}) 与 外部主键数目({tbref.Primarys.Length}) 不相同"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + } + for (var a = 0; nvref.Exception == null && a < tbref.Primarys.Length; a++) + { + var findtbrefPkCsName = tbref.Primarys[a].CsName.TrimStart('_'); + if (findtbrefPkCsName.StartsWith(tbref.Type.Name, StringComparison.CurrentCultureIgnoreCase)) findtbrefPkCsName = findtbrefPkCsName.Substring(tbref.Type.Name.Length).TrimStart('_'); - nvref.Columns.Add(trycol); - nvref.RefColumns.Add(tbref.Primarys[a]); + var trycol = bindColumns.Any() ? bindColumns[a] : null; + if (trycol == null && + trytb.ColumnsByCs.TryGetValue($"{pnv.Name}{findtbrefPkCsName}", out trycol) == false && //骆峰命名 + trytb.ColumnsByCs.TryGetValue($"{pnv.Name}_{findtbrefPkCsName}", out trycol) == false && //下划线命名 + //tbref.Primarys.Length == 1 && + trytb.ColumnsByCs.TryGetValue($"{pnv.Name}_Id", out trycol) == false && + trytb.ColumnsByCs.TryGetValue($"{pnv.Name}Id", out trycol) == false + ) + { + //一对一,主键与主键查找 + if (isOnoToOne) + { + var trytbpks = trytb.Primarys.Where(z => z.CsType == tbref.Primarys[a].CsType); //一对一,按类型 + if (trytbpks.Count() == 1) trycol = trytbpks.First(); + else + { + trytbpks = trytb.Primarys.Where(z => string.Compare(z.CsName, tbref.Primarys[a].CsName, true) == 0); //一对一,按主键名相同 + if (trytbpks.Count() == 1) trycol = trytbpks.First(); + else + { + trytbpks = trytb.Primarys.Where(z => string.Compare(z.CsName, $"{tbref.CsName}{tbref.Primarys[a].CsName}", true) == 0); //一对一,主键名 = 表+主键名 + if (trytbpks.Count() == 1) trycol = trytbpks.First(); + else + { + trytbpks = trytb.Primarys.Where(z => string.Compare(z.CsName, $"{tbref.CsName}_{tbref.Primarys[a].CsName}", true) == 0); //一对一,主键名 = 表+_主键名 + if (trytbpks.Count() == 1) trycol = trytbpks.First(); + } + } + } + } + } + if (trycol != null && trycol.CsType.NullableTypeOrThis() != tbref.Primarys[a].CsType) + { + nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 解析错误,{trytb.CsName}.{trycol.CsName} 和 {tbref.CsName}.{tbref.Primarys[a].CsName} 类型不一致"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } + if (trycol == null) + { + nvref.Exception = new Exception($"导航属性 {trytbTypeName}.{pnv.Name} 没有找到对应的字段,如:{pnv.Name}{findtbrefPkCsName}、{pnv.Name}_{findtbrefPkCsName}。或者使用 [Navigate] 特性指定关系映射。"); + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + //if (isLazy) throw nvref.Exception; + break; + } - if (isLazy && nvref.Exception == null) { - if (a > 0) lmbdWhere.Append(" && "); - lmbdWhere.Append("a.").Append(tbref.Primarys[a].CsName).Append(" == this.").Append(trycol.CsName); - } - } - if (nvref.Columns.Count > 0 && nvref.RefColumns.Count > 0) { - nvref.RefEntityType = tbref.Type; - nvref.RefType = isOnoToOne ? TableRefType.OneToOne : TableRefType.ManyToOne; - trytb.AddOrUpdateTableRef(pnv.Name, nvref); - } + nvref.Columns.Add(trycol); + nvref.RefColumns.Add(tbref.Primarys[a]); - if (isLazy) { - cscode.Append(" private bool __lazy__").Append(pnv.Name).AppendLine(" = false;") - .Append(" public override ").Append(propTypeName).Append(" ").Append(pnv.Name).AppendLine(" {"); - if (vp.Item2) { //get 重写 - cscode.Append(" get {\r\n") - .Append(" if (base.").Append(pnv.Name).Append(" == null && __lazy__").Append(pnv.Name).AppendLine(" == false) {"); + if (isLazy && nvref.Exception == null) + { + if (a > 0) lmbdWhere.Append(" && "); + lmbdWhere.Append("a.").Append(tbref.Primarys[a].CsName).Append(" == this.").Append(trycol.CsName); + } + } + if (nvref.Columns.Count > 0 && nvref.RefColumns.Count > 0) + { + nvref.RefEntityType = tbref.Type; + nvref.RefType = isOnoToOne ? TableRefType.OneToOne : TableRefType.ManyToOne; + trytb.AddOrUpdateTableRef(pnv.Name, nvref); + } - if (nvref.Exception == null) - cscode.Append(" base.").Append(pnv.Name).Append(" = __fsql_orm__.Select<").Append(propTypeName).Append(">().Where(a => ").Append(lmbdWhere.ToString()).AppendLine(").ToOne();") - .Append(" __lazy__").Append(pnv.Name).AppendLine(" = true;"); - else - cscode.Append(" throw new Exception(\"").Append(nvref.Exception.Message.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")).AppendLine("\");"); - - cscode - .Append(" }\r\n") - .Append(" return base.").Append(pnv.Name).AppendLine(";") - .Append(" }\r\n"); - } - if (vp.Item3) { //set 重写 - cscode.Append(" set {\r\n") - .Append(" base.").Append(pnv.Name).AppendLine(" = value;") - .Append(" __lazy__").Append(pnv.Name).AppendLine(" = true;") - .Append(" }\r\n"); - } - cscode.AppendLine(" }"); - } - } + if (isLazy) + { + cscode.Append(" private bool __lazy__").Append(pnv.Name).AppendLine(" = false;") + .Append(" public override ").Append(propTypeName).Append(" ").Append(pnv.Name).AppendLine(" {"); + if (vp.Item2) + { //get 重写 + cscode.Append(" get {\r\n") + .Append(" if (base.").Append(pnv.Name).Append(" == null && __lazy__").Append(pnv.Name).AppendLine(" == false) {"); - if (isLazy)++overrieds; - } - if (overrieds > 0) { - cscode.AppendLine("}"); - Assembly assembly = null; - if (MethodLazyLoadingComplier.Value == null) throw new Exception("【延时加载】功能需要安装 FreeSql.Extensions.LazyLoading.dll,可前往 nuget 下载"); - try { - assembly = MethodLazyLoadingComplier.Value.Invoke(null, new object[] { cscode.ToString() }) as Assembly; - } catch (Exception ex) { - throw new Exception($"【延时加载】{trytbTypeName} 编译错误:{ex.Message}\r\n\r\n{cscode}"); - } - var type = assembly.DefinedTypes.Where(a => a.FullName.EndsWith(trytbTypeLazyName)).FirstOrDefault(); - trytb.TypeLazy = type; - trytb.TypeLazySetOrm = type.GetProperty("__fsql_orm__", BindingFlags.Instance | BindingFlags.NonPublic).GetSetMethod(true); - tbc.AddOrUpdate(type, trytb, (oldkey, oldval) => trytb); - } - #endregion + if (nvref.Exception == null) + cscode.Append(" base.").Append(pnv.Name).Append(" = __fsql_orm__.Select<").Append(propTypeName).Append(">().Where(a => ").Append(lmbdWhere.ToString()).AppendLine(").ToOne();") + .Append(" __lazy__").Append(pnv.Name).AppendLine(" = true;"); + else + cscode.Append(" throw new Exception(\"").Append(nvref.Exception.Message.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")).AppendLine("\");"); - return tbc.TryGetValue(entity, out var trytb2) ? trytb2 : trytb; - } - static Lazy MethodLazyLoadingComplier = new Lazy(() => { - var type = Type.GetType("FreeSql.Extensions.LazyLoading.LazyLoadingComplier,FreeSql.Extensions.LazyLoading"); - return type?.GetMethod("CompileCode"); - }); + cscode + .Append(" }\r\n") + .Append(" return base.").Append(pnv.Name).AppendLine(";") + .Append(" }\r\n"); + } + if (vp.Item3) + { //set 重写 + cscode.Append(" set {\r\n") + .Append(" base.").Append(pnv.Name).AppendLine(" = value;") + .Append(" __lazy__").Append(pnv.Name).AppendLine(" = true;") + .Append(" }\r\n"); + } + cscode.AppendLine(" }"); + } + } - public static T[] GetDbParamtersByObject(string sql, object obj, string paramPrefix, Func constructorParamter) { - if (string.IsNullOrEmpty(sql) || obj == null) return new T[0]; - var ttype = typeof(T); - var type = obj.GetType(); - if (type == ttype) return new[] { (T)Convert.ChangeType(obj, type) }; - var ret = new List(); - var ps = type.GetProperties(); - foreach (var p in ps) { - if (sql.IndexOf($"{paramPrefix}{p.Name}", StringComparison.CurrentCultureIgnoreCase) == -1) continue; - var pvalue = p.GetValue(obj); - if (p.PropertyType == ttype) ret.Add((T)Convert.ChangeType(pvalue, ttype)); - else ret.Add(constructorParamter(p.Name, p.PropertyType, pvalue)); - } - return ret.ToArray(); - } + if (isLazy) ++overrieds; + } + if (overrieds > 0) + { + cscode.AppendLine("}"); + Assembly assembly = null; + if (MethodLazyLoadingComplier.Value == null) throw new Exception("【延时加载】功能需要安装 FreeSql.Extensions.LazyLoading.dll,可前往 nuget 下载"); + try + { + assembly = MethodLazyLoadingComplier.Value.Invoke(null, new object[] { cscode.ToString() }) as Assembly; + } + catch (Exception ex) + { + throw new Exception($"【延时加载】{trytbTypeName} 编译错误:{ex.Message}\r\n\r\n{cscode}"); + } + var type = assembly.DefinedTypes.Where(a => a.FullName.EndsWith(trytbTypeLazyName)).FirstOrDefault(); + trytb.TypeLazy = type; + trytb.TypeLazySetOrm = type.GetProperty("__fsql_orm__", BindingFlags.Instance | BindingFlags.NonPublic).GetSetMethod(true); + tbc.AddOrUpdate(type, trytb, (oldkey, oldval) => trytb); + } + #endregion - public static Dictionary dicExecuteArrayRowReadClassOrTuple = new Dictionary { - [typeof(bool)] = true, - [typeof(sbyte)] = true, - [typeof(short)] = true, - [typeof(int)] = true, - [typeof(long)] = true, - [typeof(byte)] = true, - [typeof(ushort)] = true, - [typeof(uint)] = true, - [typeof(ulong)] = true, - [typeof(double)] = true, - [typeof(float)] = true, - [typeof(decimal)] = true, - [typeof(TimeSpan)] = true, - [typeof(DateTime)] = true, - [typeof(DateTimeOffset)] = true, - [typeof(byte[])] = true, - [typeof(string)] = true, - [typeof(Guid)] = true, - //[typeof(MygisPoint)] = true, - //[typeof(MygisLineString)] = true, - //[typeof(MygisPolygon)] = true, - //[typeof(MygisMultiPoint)] = true, - //[typeof(MygisMultiLineString)] = true, - //[typeof(MygisMultiPolygon)] = true, - //[typeof(BitArray)] = true, - //[typeof(NpgsqlPoint)] = true, - //[typeof(NpgsqlLine)] = true, - //[typeof(NpgsqlLSeg)] = true, - //[typeof(NpgsqlBox)] = true, - //[typeof(NpgsqlPath)] = true, - //[typeof(NpgsqlPolygon)] = true, - //[typeof(NpgsqlCircle)] = true, - //[typeof((IPAddress Address, int Subnet))] = true, - //[typeof(IPAddress)] = true, - //[typeof(PhysicalAddress)] = true, - //[typeof(NpgsqlRange)] = true, - //[typeof(NpgsqlRange)] = true, - //[typeof(NpgsqlRange)] = true, - //[typeof(NpgsqlRange)] = true, - //[typeof(PostgisPoint)] = true, - //[typeof(PostgisLineString)] = true, - //[typeof(PostgisPolygon)] = true, - //[typeof(PostgisMultiPoint)] = true, - //[typeof(PostgisMultiLineString)] = true, - //[typeof(PostgisMultiPolygon)] = true, - //[typeof(PostgisGeometry)] = true, - //[typeof(PostgisGeometryCollection)] = true, - //[typeof(Dictionary)] = true, - //[typeof(JToken)] = true, - //[typeof(JObject)] = true, - //[typeof(JArray)] = true, - }; - internal static ConcurrentDictionary>> _dicExecuteArrayRowReadClassOrTuple = new ConcurrentDictionary>>(); - internal class RowInfo { - public object Value { get; set; } - public int DataIndex { get; set; } - public RowInfo(object value, int dataIndex) { - this.Value = value; - this.DataIndex = dataIndex; - } - public static ConstructorInfo Constructor = typeof(RowInfo).GetConstructor(new[] { typeof(object), typeof(int) }); - public static PropertyInfo PropertyValue = typeof(RowInfo).GetProperty("Value"); - public static PropertyInfo PropertyDataIndex = typeof(RowInfo).GetProperty("DataIndex"); - } - internal static MethodInfo MethodDataReaderGetValue = typeof(DbDataReader).GetMethod("GetValue"); - internal static RowInfo ExecuteArrayRowReadClassOrTuple(string flagStr, Type typeOrg, int[] indexes, DbDataReader row, int dataIndex, CommonUtils _commonUtils) { - if (string.IsNullOrEmpty(flagStr)) flagStr = "all"; - var func = _dicExecuteArrayRowReadClassOrTuple - .GetOrAdd(flagStr, flag => new ConcurrentDictionary>()) - .GetOrAdd(typeOrg, type => { - var returnTarget = Expression.Label(typeof(RowInfo)); - var typeExp = Expression.Parameter(typeof(Type), "type"); - var indexesExp = Expression.Parameter(typeof(int[]), "indexes"); - var rowExp = Expression.Parameter(typeof(DbDataReader), "row"); - var dataIndexExp = Expression.Parameter(typeof(int), "dataIndex"); - var commonUtilExp = Expression.Parameter(typeof(CommonUtils), "commonUtil"); + return tbc.TryGetValue(entity, out var trytb2) ? trytb2 : trytb; + } + static Lazy MethodLazyLoadingComplier = new Lazy(() => + { + var type = Type.GetType("FreeSql.Extensions.LazyLoading.LazyLoadingComplier,FreeSql.Extensions.LazyLoading"); + return type?.GetMethod("CompileCode"); + }); - if (type.IsArray) return Expression.Lambda>( - Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(type, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { typeExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), - Expression.Add(dataIndexExp, Expression.Constant(1)) - ), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); + public static T[] GetDbParamtersByObject(string sql, object obj, string paramPrefix, Func constructorParamter) + { + if (string.IsNullOrEmpty(sql) || obj == null) return new T[0]; + var ttype = typeof(T); + var type = obj.GetType(); + if (type == ttype) return new[] { (T)Convert.ChangeType(obj, type) }; + var ret = new List(); + var ps = type.GetProperties(); + foreach (var p in ps) + { + if (sql.IndexOf($"{paramPrefix}{p.Name}", StringComparison.CurrentCultureIgnoreCase) == -1) continue; + var pvalue = p.GetValue(obj); + if (p.PropertyType == ttype) ret.Add((T)Convert.ChangeType(pvalue, ttype)); + else ret.Add(constructorParamter(p.Name, p.PropertyType, pvalue)); + } + return ret.ToArray(); + } - var typeGeneric = type; - if (typeGeneric.IsNullableType()) typeGeneric = type.GenericTypeArguments.First(); - if (typeGeneric.IsEnum || - dicExecuteArrayRowReadClassOrTuple.ContainsKey(typeGeneric)) - return Expression.Lambda>( - Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(type, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { typeExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), - Expression.Add(dataIndexExp, Expression.Constant(1)) - ), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); + public static Dictionary dicExecuteArrayRowReadClassOrTuple = new Dictionary + { + [typeof(bool)] = true, + [typeof(sbyte)] = true, + [typeof(short)] = true, + [typeof(int)] = true, + [typeof(long)] = true, + [typeof(byte)] = true, + [typeof(ushort)] = true, + [typeof(uint)] = true, + [typeof(ulong)] = true, + [typeof(double)] = true, + [typeof(float)] = true, + [typeof(decimal)] = true, + [typeof(TimeSpan)] = true, + [typeof(DateTime)] = true, + [typeof(DateTimeOffset)] = true, + [typeof(byte[])] = true, + [typeof(string)] = true, + [typeof(Guid)] = true, + //[typeof(MygisPoint)] = true, + //[typeof(MygisLineString)] = true, + //[typeof(MygisPolygon)] = true, + //[typeof(MygisMultiPoint)] = true, + //[typeof(MygisMultiLineString)] = true, + //[typeof(MygisMultiPolygon)] = true, + //[typeof(BitArray)] = true, + //[typeof(NpgsqlPoint)] = true, + //[typeof(NpgsqlLine)] = true, + //[typeof(NpgsqlLSeg)] = true, + //[typeof(NpgsqlBox)] = true, + //[typeof(NpgsqlPath)] = true, + //[typeof(NpgsqlPolygon)] = true, + //[typeof(NpgsqlCircle)] = true, + //[typeof((IPAddress Address, int Subnet))] = true, + //[typeof(IPAddress)] = true, + //[typeof(PhysicalAddress)] = true, + //[typeof(NpgsqlRange)] = true, + //[typeof(NpgsqlRange)] = true, + //[typeof(NpgsqlRange)] = true, + //[typeof(NpgsqlRange)] = true, + //[typeof(PostgisPoint)] = true, + //[typeof(PostgisLineString)] = true, + //[typeof(PostgisPolygon)] = true, + //[typeof(PostgisMultiPoint)] = true, + //[typeof(PostgisMultiLineString)] = true, + //[typeof(PostgisMultiPolygon)] = true, + //[typeof(PostgisGeometry)] = true, + //[typeof(PostgisGeometryCollection)] = true, + //[typeof(Dictionary)] = true, + //[typeof(JToken)] = true, + //[typeof(JObject)] = true, + //[typeof(JArray)] = true, + }; + internal static ConcurrentDictionary>> _dicExecuteArrayRowReadClassOrTuple = new ConcurrentDictionary>>(); + internal class RowInfo + { + public object Value { get; set; } + public int DataIndex { get; set; } + public RowInfo(object value, int dataIndex) + { + this.Value = value; + this.DataIndex = dataIndex; + } + public static ConstructorInfo Constructor = typeof(RowInfo).GetConstructor(new[] { typeof(object), typeof(int) }); + public static PropertyInfo PropertyValue = typeof(RowInfo).GetProperty("Value"); + public static PropertyInfo PropertyDataIndex = typeof(RowInfo).GetProperty("DataIndex"); + } + internal static MethodInfo MethodDataReaderGetValue = typeof(DbDataReader).GetMethod("GetValue"); + internal static RowInfo ExecuteArrayRowReadClassOrTuple(string flagStr, Type typeOrg, int[] indexes, DbDataReader row, int dataIndex, CommonUtils _commonUtils) + { + if (string.IsNullOrEmpty(flagStr)) flagStr = "all"; + var func = _dicExecuteArrayRowReadClassOrTuple + .GetOrAdd(flagStr, flag => new ConcurrentDictionary>()) + .GetOrAdd(typeOrg, type => + { + var returnTarget = Expression.Label(typeof(RowInfo)); + var typeExp = Expression.Parameter(typeof(Type), "type"); + var indexesExp = Expression.Parameter(typeof(int[]), "indexes"); + var rowExp = Expression.Parameter(typeof(DbDataReader), "row"); + var dataIndexExp = Expression.Parameter(typeof(int), "dataIndex"); + var commonUtilExp = Expression.Parameter(typeof(CommonUtils), "commonUtil"); - if (type.Namespace == "System" && (type.FullName == "System.String" || type.IsValueType)) { //值类型,或者元组 - bool isTuple = type.Name.StartsWith("ValueTuple`"); - if (isTuple) { - var ret2Exp = Expression.Variable(type, "ret"); - var read2Exp = Expression.Variable(typeof(RowInfo), "read"); - var read2ExpValue = Expression.MakeMemberAccess(read2Exp, RowInfo.PropertyValue); - var read2ExpDataIndex = Expression.MakeMemberAccess(read2Exp, RowInfo.PropertyDataIndex); - var block2Exp = new List(); + if (type.IsArray) return Expression.Lambda>( + Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(type, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { typeExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), + Expression.Add(dataIndexExp, Expression.Constant(1)) + ), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); - var fields = type.GetFields(); - foreach (var field in fields) { - Expression read2ExpAssign = null; //加速缓存 - if (field.FieldType.IsArray) read2ExpAssign = Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(field.FieldType, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(field.FieldType), Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), - Expression.Add(dataIndexExp, Expression.Constant(1)) - ); - else { - var fieldtypeGeneric = field.FieldType; - if (fieldtypeGeneric.IsNullableType()) fieldtypeGeneric = fieldtypeGeneric.GenericTypeArguments.First(); - if (fieldtypeGeneric.IsEnum || - dicExecuteArrayRowReadClassOrTuple.ContainsKey(fieldtypeGeneric)) read2ExpAssign = Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(field.FieldType, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(field.FieldType), Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), - Expression.Add(dataIndexExp, Expression.Constant(1)) - ); - else { - read2ExpAssign = Expression.Call(MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(flagStr), Expression.Constant(field.FieldType), indexesExp, rowExp, dataIndexExp, commonUtilExp }); - } - } - block2Exp.AddRange(new Expression[] { + var typeGeneric = type; + if (typeGeneric.IsNullableType()) typeGeneric = type.GenericTypeArguments.First(); + if (typeGeneric.IsEnum || + dicExecuteArrayRowReadClassOrTuple.ContainsKey(typeGeneric)) + return Expression.Lambda>( + Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(type, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { typeExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), + Expression.Add(dataIndexExp, Expression.Constant(1)) + ), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); + + if (type.Namespace == "System" && (type.FullName == "System.String" || type.IsValueType)) + { //值类型,或者元组 + bool isTuple = type.Name.StartsWith("ValueTuple`"); + if (isTuple) + { + var ret2Exp = Expression.Variable(type, "ret"); + var read2Exp = Expression.Variable(typeof(RowInfo), "read"); + var read2ExpValue = Expression.MakeMemberAccess(read2Exp, RowInfo.PropertyValue); + var read2ExpDataIndex = Expression.MakeMemberAccess(read2Exp, RowInfo.PropertyDataIndex); + var block2Exp = new List(); + + var fields = type.GetFields(); + foreach (var field in fields) + { + Expression read2ExpAssign = null; //加速缓存 + if (field.FieldType.IsArray) read2ExpAssign = Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(field.FieldType, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(field.FieldType), Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), + Expression.Add(dataIndexExp, Expression.Constant(1)) + ); + else + { + var fieldtypeGeneric = field.FieldType; + if (fieldtypeGeneric.IsNullableType()) fieldtypeGeneric = fieldtypeGeneric.GenericTypeArguments.First(); + if (fieldtypeGeneric.IsEnum || + dicExecuteArrayRowReadClassOrTuple.ContainsKey(fieldtypeGeneric)) read2ExpAssign = Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(field.FieldType, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(field.FieldType), Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), + Expression.Add(dataIndexExp, Expression.Constant(1)) + ); + else + { + read2ExpAssign = Expression.Call(MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(flagStr), Expression.Constant(field.FieldType), indexesExp, rowExp, dataIndexExp, commonUtilExp }); + } + } + block2Exp.AddRange(new Expression[] { //Expression.TryCatch(Expression.Block( // typeof(void), Expression.Assign(read2Exp, read2ExpAssign), - Expression.IfThen(Expression.GreaterThan(read2ExpDataIndex, dataIndexExp), - Expression.Assign(dataIndexExp, read2ExpDataIndex)), - Expression.IfThenElse(Expression.Equal(read2ExpValue, Expression.Constant(null)), - Expression.Assign(Expression.MakeMemberAccess(ret2Exp, field), Expression.Default(field.FieldType)), - Expression.Assign(Expression.MakeMemberAccess(ret2Exp, field), Expression.Convert(read2ExpValue, field.FieldType))) + Expression.IfThen(Expression.GreaterThan(read2ExpDataIndex, dataIndexExp), + Expression.Assign(dataIndexExp, read2ExpDataIndex)), + Expression.IfThenElse(Expression.Equal(read2ExpValue, Expression.Constant(null)), + Expression.Assign(Expression.MakeMemberAccess(ret2Exp, field), Expression.Default(field.FieldType)), + Expression.Assign(Expression.MakeMemberAccess(ret2Exp, field), Expression.Convert(read2ExpValue, field.FieldType))) //), //Expression.Catch(typeof(Exception), Expression.Block( // Expression.IfThen(Expression.Equal(read2ExpDataIndex, Expression.Constant(0)), Expression.Throw(Expression.Constant(new Exception(field.Name + "," + 0)))), @@ -878,636 +1006,666 @@ namespace FreeSql.Internal { // ) //)) }); - } - block2Exp.AddRange(new Expression[] { - Expression.Return(returnTarget, Expression.New(RowInfo.Constructor, Expression.Convert(ret2Exp, typeof(object)), dataIndexExp)), - Expression.Label(returnTarget, Expression.Default(typeof(RowInfo))) - }); - return Expression.Lambda>( - Expression.Block(new[] { ret2Exp, read2Exp }, block2Exp), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); - } - var rowLenExp = Expression.ArrayLength(rowExp); - return Expression.Lambda>( - Expression.Block( - Expression.IfThen( - Expression.LessThan(dataIndexExp, rowLenExp), - Expression.Return(returnTarget, Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(type, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { typeExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), - Expression.Add(dataIndexExp, Expression.Constant(1)))) - ), - Expression.Label(returnTarget, Expression.Default(typeof(RowInfo))) - ), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); - } + } + block2Exp.AddRange(new Expression[] { + Expression.Return(returnTarget, Expression.New(RowInfo.Constructor, Expression.Convert(ret2Exp, typeof(object)), dataIndexExp)), + Expression.Label(returnTarget, Expression.Default(typeof(RowInfo))) + }); + return Expression.Lambda>( + Expression.Block(new[] { ret2Exp, read2Exp }, block2Exp), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); + } + var rowLenExp = Expression.ArrayLength(rowExp); + return Expression.Lambda>( + Expression.Block( + Expression.IfThen( + Expression.LessThan(dataIndexExp, rowLenExp), + Expression.Return(returnTarget, Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(type, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { typeExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp) }), + Expression.Add(dataIndexExp, Expression.Constant(1)))) + ), + Expression.Label(returnTarget, Expression.Default(typeof(RowInfo))) + ), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); + } - if (type == typeof(object) && indexes != null) { - Func dynamicFunc = (type2, indexes2, row2, dataindex2, commonUtils2) => { - //dynamic expando = new DynamicDictionary(); //动态类型字段 可读可写 - var expandodic = new Dictionary();// (IDictionary)expando; - var fc = row2.FieldCount; - for (var a = 0; a < fc; a++) - //expando[row2.GetName(a)] = row2.GetValue(a); - expandodic.Add(row2.GetName(a), row2.GetValue(a)); - //expando = expandodic; - return new RowInfo(expandodic, fc); - }; - return dynamicFunc;// Expression.Lambda>(null); - } + if (type == typeof(object) && indexes != null) + { + Func dynamicFunc = (type2, indexes2, row2, dataindex2, commonUtils2) => + { + //dynamic expando = new DynamicDictionary(); //动态类型字段 可读可写 + var expandodic = new Dictionary();// (IDictionary)expando; + var fc = row2.FieldCount; + for (var a = 0; a < fc; a++) + //expando[row2.GetName(a)] = row2.GetValue(a); + expandodic.Add(row2.GetName(a), row2.GetValue(a)); + //expando = expandodic; + return new RowInfo(expandodic, fc); + }; + return dynamicFunc;// Expression.Lambda>(null); + } - //类注入属性 - var typetb = GetTableByEntity(type, _commonUtils); - var retExp = Expression.Variable(type, "ret"); - var readExp = Expression.Variable(typeof(RowInfo), "read"); - var readExpValue = Expression.MakeMemberAccess(readExp, RowInfo.PropertyValue); - var readExpDataIndex = Expression.MakeMemberAccess(readExp, RowInfo.PropertyDataIndex); - var readExpValueParms = new List(); - var readExpsIndex = Expression.Variable(typeof(int), "readsIndex"); - var tryidxExp = Expression.Variable(typeof(int), "tryidx"); - var readpknullExp = Expression.Variable(typeof(bool), "isnull2"); - var readpkvalExp = Expression.Variable(typeof(object), "isnull3val"); - var indexesLengthExp = Expression.Variable(typeof(int), "indexesLength"); - var blockExp = new List(); - var ctor = type.GetConstructor(new Type[0]) ?? type.GetConstructors().First(); - var ctorParms = ctor.GetParameters(); - if (ctorParms.Length > 0) { - blockExp.AddRange(new Expression[] { - Expression.Assign(readpknullExp, Expression.Constant(false)) - }); - foreach (var ctorParm in ctorParms) { - if (typetb.ColumnsByCsIgnore.ContainsKey(ctorParm.Name)) continue; - var readType = typetb.ColumnsByCs.TryGetValue(ctorParm.Name, out var trycol) ? trycol.Attribute.MapType : ctorParm.ParameterType; + //类注入属性 + var typetb = GetTableByEntity(type, _commonUtils); + var retExp = Expression.Variable(type, "ret"); + var readExp = Expression.Variable(typeof(RowInfo), "read"); + var readExpValue = Expression.MakeMemberAccess(readExp, RowInfo.PropertyValue); + var readExpDataIndex = Expression.MakeMemberAccess(readExp, RowInfo.PropertyDataIndex); + var readExpValueParms = new List(); + var readExpsIndex = Expression.Variable(typeof(int), "readsIndex"); + var tryidxExp = Expression.Variable(typeof(int), "tryidx"); + var readpknullExp = Expression.Variable(typeof(bool), "isnull2"); + var readpkvalExp = Expression.Variable(typeof(object), "isnull3val"); + var indexesLengthExp = Expression.Variable(typeof(int), "indexesLength"); + var blockExp = new List(); + var ctor = type.GetConstructor(new Type[0]) ?? type.GetConstructors().First(); + var ctorParms = ctor.GetParameters(); + if (ctorParms.Length > 0) + { + blockExp.AddRange(new Expression[] { + Expression.Assign(readpknullExp, Expression.Constant(false)) + }); + foreach (var ctorParm in ctorParms) + { + if (typetb.ColumnsByCsIgnore.ContainsKey(ctorParm.Name)) continue; + var readType = typetb.ColumnsByCs.TryGetValue(ctorParm.Name, out var trycol) ? trycol.Attribute.MapType : ctorParm.ParameterType; - var ispkExp = new List(); - Expression readVal = Expression.Assign(readpkvalExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)); - Expression readExpAssign = null; //加速缓存 - if (readType.IsArray) readExpAssign = Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(readType, readpkvalExp), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(readType), readpkvalExp }), - Expression.Add(dataIndexExp, Expression.Constant(1)) - ); - else { - var proptypeGeneric = readType; - if (proptypeGeneric.IsNullableType()) proptypeGeneric = proptypeGeneric.GenericTypeArguments.First(); - if (proptypeGeneric.IsEnum || - dicExecuteArrayRowReadClassOrTuple.ContainsKey(proptypeGeneric)) { + var ispkExp = new List(); + Expression readVal = Expression.Assign(readpkvalExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp)); + Expression readExpAssign = null; //加速缓存 + if (readType.IsArray) readExpAssign = Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(readType, readpkvalExp), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(readType), readpkvalExp }), + Expression.Add(dataIndexExp, Expression.Constant(1)) + ); + else + { + var proptypeGeneric = readType; + if (proptypeGeneric.IsNullableType()) proptypeGeneric = proptypeGeneric.GenericTypeArguments.First(); + if (proptypeGeneric.IsEnum || + dicExecuteArrayRowReadClassOrTuple.ContainsKey(proptypeGeneric)) + { - //判断主键为空,则整个对象不读取 - //blockExp.Add(Expression.Assign(readpkvalExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp))); - if (trycol?.Attribute.IsPrimary == true) { - ispkExp.Add( - Expression.IfThen( - Expression.AndAlso( - Expression.IsFalse(readpknullExp), - Expression.Or( - Expression.Equal(readpkvalExp, Expression.Constant(DBNull.Value)), - Expression.Equal(readpkvalExp, Expression.Constant(null)) - ) - ), - Expression.Assign(readpknullExp, Expression.Constant(true)) - ) - ); - } + //判断主键为空,则整个对象不读取 + //blockExp.Add(Expression.Assign(readpkvalExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp))); + if (trycol?.Attribute.IsPrimary == true) + { + ispkExp.Add( + Expression.IfThen( + Expression.AndAlso( + Expression.IsFalse(readpknullExp), + Expression.Or( + Expression.Equal(readpkvalExp, Expression.Constant(DBNull.Value)), + Expression.Equal(readpkvalExp, Expression.Constant(null)) + ) + ), + Expression.Assign(readpknullExp, Expression.Constant(true)) + ) + ); + } - readExpAssign = Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(readType, readpkvalExp), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(readType), readpkvalExp }), - Expression.Add(dataIndexExp, Expression.Constant(1)) - ); - } else { - readExpAssign = Expression.New(RowInfo.Constructor, - Expression.MakeMemberAccess(Expression.Call(MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(flagStr), Expression.Constant(readType), indexesExp, rowExp, dataIndexExp, commonUtilExp }), RowInfo.PropertyValue), - Expression.Add(dataIndexExp, Expression.Constant(1))); - } - } - var varctorParm = Expression.Variable(ctorParm.ParameterType, $"ctorParm{ctorParm.Name}"); - readExpValueParms.Add(varctorParm); + readExpAssign = Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(readType, readpkvalExp), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(readType), readpkvalExp }), + Expression.Add(dataIndexExp, Expression.Constant(1)) + ); + } + else + { + readExpAssign = Expression.New(RowInfo.Constructor, + Expression.MakeMemberAccess(Expression.Call(MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(flagStr), Expression.Constant(readType), indexesExp, rowExp, dataIndexExp, commonUtilExp }), RowInfo.PropertyValue), + Expression.Add(dataIndexExp, Expression.Constant(1))); + } + } + var varctorParm = Expression.Variable(ctorParm.ParameterType, $"ctorParm{ctorParm.Name}"); + readExpValueParms.Add(varctorParm); - if (trycol != null && trycol.Attribute.MapType != ctorParm.ParameterType) - ispkExp.Add(Expression.Assign(readExpValue, GetDataReaderValueBlockExpression(ctorParm.ParameterType, readExpValue))); + if (trycol != null && trycol.Attribute.MapType != ctorParm.ParameterType) + ispkExp.Add(Expression.Assign(readExpValue, GetDataReaderValueBlockExpression(ctorParm.ParameterType, readExpValue))); - ispkExp.Add( - Expression.IfThen( - Expression.IsFalse(readpknullExp), - Expression.IfThenElse( - Expression.Equal(readExpValue, Expression.Constant(null)), - Expression.Assign(varctorParm, Expression.Default(ctorParm.ParameterType)), - Expression.Assign(varctorParm, Expression.Convert(readExpValue, ctorParm.ParameterType)) - ) - ) - ); + ispkExp.Add( + Expression.IfThen( + Expression.IsFalse(readpknullExp), + Expression.IfThenElse( + Expression.Equal(readExpValue, Expression.Constant(null)), + Expression.Assign(varctorParm, Expression.Default(ctorParm.ParameterType)), + Expression.Assign(varctorParm, Expression.Convert(readExpValue, ctorParm.ParameterType)) + ) + ) + ); - blockExp.AddRange(new Expression[] { - Expression.Assign(tryidxExp, dataIndexExp), - readVal, - Expression.Assign(readExp, readExpAssign), - Expression.IfThen(Expression.GreaterThan(readExpDataIndex, dataIndexExp), - Expression.Assign(dataIndexExp, readExpDataIndex) - ), - Expression.Block(ispkExp) - }); - } - blockExp.Add( - Expression.IfThen( - Expression.IsFalse(readpknullExp), - Expression.Assign(retExp, Expression.New(ctor, readExpValueParms)) - ) - ); - } else { - blockExp.AddRange(new Expression[] { - Expression.Assign(retExp, Expression.New(ctor)), - Expression.Assign(indexesLengthExp, Expression.Constant(0)), - Expression.IfThen( - Expression.NotEqual(indexesExp, Expression.Constant(null)), - Expression.Assign(indexesLengthExp, Expression.ArrayLength(indexesExp)) - ), - Expression.Assign(readpknullExp, Expression.Constant(false)) - }); - - var props = type.GetProperties();//.ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase); - var propIndex = 0; - foreach (var prop in props) { - if (typetb.ColumnsByCsIgnore.ContainsKey(prop.Name)) { - ++propIndex; - continue; - } - var readType = typetb.ColumnsByCs.TryGetValue(prop.Name, out var trycol) ? trycol.Attribute.MapType : prop.PropertyType; + blockExp.AddRange(new Expression[] { + Expression.Assign(tryidxExp, dataIndexExp), + readVal, + Expression.Assign(readExp, readExpAssign), + Expression.IfThen(Expression.GreaterThan(readExpDataIndex, dataIndexExp), + Expression.Assign(dataIndexExp, readExpDataIndex) + ), + Expression.Block(ispkExp) + }); + } + blockExp.Add( + Expression.IfThen( + Expression.IsFalse(readpknullExp), + Expression.Assign(retExp, Expression.New(ctor, readExpValueParms)) + ) + ); + } + else + { + blockExp.AddRange(new Expression[] { + Expression.Assign(retExp, Expression.New(ctor)), + Expression.Assign(indexesLengthExp, Expression.Constant(0)), + Expression.IfThen( + Expression.NotEqual(indexesExp, Expression.Constant(null)), + Expression.Assign(indexesLengthExp, Expression.ArrayLength(indexesExp)) + ), + Expression.Assign(readpknullExp, Expression.Constant(false)) + }); - var ispkExp = new List(); - var propGetSetMethod = prop.GetSetMethod(); - Expression readVal = Expression.Assign(readpkvalExp, Expression.Call(rowExp, MethodDataReaderGetValue, tryidxExp)); - Expression readExpAssign = null; //加速缓存 - if (readType.IsArray) readExpAssign = Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(readType, readpkvalExp), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(readType), readpkvalExp }), - Expression.Add(tryidxExp, Expression.Constant(1)) - ); - else { - var proptypeGeneric = readType; - if (proptypeGeneric.IsNullableType()) proptypeGeneric = proptypeGeneric.GenericTypeArguments.First(); - if (proptypeGeneric.IsEnum || - dicExecuteArrayRowReadClassOrTuple.ContainsKey(proptypeGeneric)) { + var props = type.GetProperties();//.ToDictionary(a => a.Name, a => a, StringComparer.CurrentCultureIgnoreCase); + var propIndex = 0; + foreach (var prop in props) + { + if (typetb.ColumnsByCsIgnore.ContainsKey(prop.Name)) + { + ++propIndex; + continue; + } + var readType = typetb.ColumnsByCs.TryGetValue(prop.Name, out var trycol) ? trycol.Attribute.MapType : prop.PropertyType; - //判断主键为空,则整个对象不读取 - //blockExp.Add(Expression.Assign(readpkvalExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp))); - if (trycol?.Attribute.IsPrimary == true) { - ispkExp.Add( - Expression.IfThen( - Expression.AndAlso( - Expression.IsFalse(readpknullExp), - Expression.Or( - Expression.Equal(readpkvalExp, Expression.Constant(DBNull.Value)), - Expression.Equal(readpkvalExp, Expression.Constant(null)) - ) - ), - Expression.Block( - Expression.Assign(readpknullExp, Expression.Constant(true)), - Expression.Assign(retExp, Expression.Constant(null, type)) - ) - ) - ); - } + var ispkExp = new List(); + var propGetSetMethod = prop.GetSetMethod(); + Expression readVal = Expression.Assign(readpkvalExp, Expression.Call(rowExp, MethodDataReaderGetValue, tryidxExp)); + Expression readExpAssign = null; //加速缓存 + if (readType.IsArray) readExpAssign = Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(readType, readpkvalExp), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(readType), readpkvalExp }), + Expression.Add(tryidxExp, Expression.Constant(1)) + ); + else + { + var proptypeGeneric = readType; + if (proptypeGeneric.IsNullableType()) proptypeGeneric = proptypeGeneric.GenericTypeArguments.First(); + if (proptypeGeneric.IsEnum || + dicExecuteArrayRowReadClassOrTuple.ContainsKey(proptypeGeneric)) + { - readExpAssign = Expression.New(RowInfo.Constructor, - GetDataReaderValueBlockExpression(readType, readpkvalExp), - //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(readType), readpkvalExp }), - Expression.Add(tryidxExp, Expression.Constant(1)) - ); - } else { - ++propIndex; - continue; - //readExpAssign = Expression.Call(MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(flagStr), Expression.Constant(readType), indexesExp, rowExp, tryidxExp }); - } - } + //判断主键为空,则整个对象不读取 + //blockExp.Add(Expression.Assign(readpkvalExp, Expression.Call(rowExp, MethodDataReaderGetValue, dataIndexExp))); + if (trycol?.Attribute.IsPrimary == true) + { + ispkExp.Add( + Expression.IfThen( + Expression.AndAlso( + Expression.IsFalse(readpknullExp), + Expression.Or( + Expression.Equal(readpkvalExp, Expression.Constant(DBNull.Value)), + Expression.Equal(readpkvalExp, Expression.Constant(null)) + ) + ), + Expression.Block( + Expression.Assign(readpknullExp, Expression.Constant(true)), + Expression.Assign(retExp, Expression.Constant(null, type)) + ) + ) + ); + } - if (trycol != null && trycol.Attribute.MapType != prop.PropertyType) - ispkExp.Add(Expression.Assign(readExpValue, GetDataReaderValueBlockExpression(prop.PropertyType, readExpValue))); + readExpAssign = Expression.New(RowInfo.Constructor, + GetDataReaderValueBlockExpression(readType, readpkvalExp), + //Expression.Call(MethodGetDataReaderValue, new Expression[] { Expression.Constant(readType), readpkvalExp }), + Expression.Add(tryidxExp, Expression.Constant(1)) + ); + } + else + { + ++propIndex; + continue; + //readExpAssign = Expression.Call(MethodExecuteArrayRowReadClassOrTuple, new Expression[] { Expression.Constant(flagStr), Expression.Constant(readType), indexesExp, rowExp, tryidxExp }); + } + } - ispkExp.Add( - Expression.IfThen( - Expression.IsFalse(readpknullExp), - Expression.IfThenElse( - Expression.Equal(readExpValue, Expression.Constant(null)), - Expression.Call(retExp, propGetSetMethod, Expression.Default(prop.PropertyType)), - Expression.Call(retExp, propGetSetMethod, Expression.Convert(readExpValue, prop.PropertyType)) - ) - ) - ); - blockExp.AddRange(new Expression[] { + if (trycol != null && trycol.Attribute.MapType != prop.PropertyType) + ispkExp.Add(Expression.Assign(readExpValue, GetDataReaderValueBlockExpression(prop.PropertyType, readExpValue))); + + ispkExp.Add( + Expression.IfThen( + Expression.IsFalse(readpknullExp), + Expression.IfThenElse( + Expression.Equal(readExpValue, Expression.Constant(null)), + Expression.Call(retExp, propGetSetMethod, Expression.Default(prop.PropertyType)), + Expression.Call(retExp, propGetSetMethod, Expression.Convert(readExpValue, prop.PropertyType)) + ) + ) + ); + blockExp.AddRange(new Expression[] { //以下注释部分为【严格读取】,会损失一点性能,使用 select * from xxx 与属性映射赋值 Expression.IfThenElse( - Expression.LessThan(Expression.Constant(propIndex), indexesLengthExp), - Expression.Assign(tryidxExp, Expression.ArrayAccess(indexesExp, Expression.Constant(propIndex))), - Expression.Assign(tryidxExp, dataIndexExp) - ), - Expression.IfThen( - Expression.GreaterThanOrEqual(tryidxExp, Expression.Constant(0)), - Expression.Block( - readVal, - Expression.Assign(readExp, readExpAssign), - Expression.IfThen(Expression.GreaterThan(readExpDataIndex, dataIndexExp), - Expression.Assign(dataIndexExp, readExpDataIndex)), - Expression.Block(ispkExp) - ) - ) - }); - ++propIndex; - } - } - blockExp.AddRange(new Expression[] { - Expression.Return(returnTarget, Expression.New(RowInfo.Constructor, retExp, dataIndexExp)), - Expression.Label(returnTarget, Expression.Default(typeof(RowInfo))) - }); - return Expression.Lambda>( - Expression.Block(new[] { retExp, readExp, tryidxExp, readpknullExp, readpkvalExp, readExpsIndex, indexesLengthExp }.Concat(readExpValueParms), blockExp), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); - }); - return func(typeOrg, indexes, row, dataIndex, _commonUtils); - } + Expression.LessThan(Expression.Constant(propIndex), indexesLengthExp), + Expression.Assign(tryidxExp, Expression.ArrayAccess(indexesExp, Expression.Constant(propIndex))), + Expression.Assign(tryidxExp, dataIndexExp) + ), + Expression.IfThen( + Expression.GreaterThanOrEqual(tryidxExp, Expression.Constant(0)), + Expression.Block( + readVal, + Expression.Assign(readExp, readExpAssign), + Expression.IfThen(Expression.GreaterThan(readExpDataIndex, dataIndexExp), + Expression.Assign(dataIndexExp, readExpDataIndex)), + Expression.Block(ispkExp) + ) + ) + }); + ++propIndex; + } + } + blockExp.AddRange(new Expression[] { + Expression.Return(returnTarget, Expression.New(RowInfo.Constructor, retExp, dataIndexExp)), + Expression.Label(returnTarget, Expression.Default(typeof(RowInfo))) + }); + return Expression.Lambda>( + Expression.Block(new[] { retExp, readExp, tryidxExp, readpknullExp, readpkvalExp, readExpsIndex, indexesLengthExp }.Concat(readExpValueParms), blockExp), new[] { typeExp, indexesExp, rowExp, dataIndexExp, commonUtilExp }).Compile(); + }); + return func(typeOrg, indexes, row, dataIndex, _commonUtils); + } - internal static MethodInfo MethodExecuteArrayRowReadClassOrTuple = typeof(Utils).GetMethod("ExecuteArrayRowReadClassOrTuple", BindingFlags.Static | BindingFlags.NonPublic); - internal static MethodInfo MethodGetDataReaderValue = typeof(Utils).GetMethod("GetDataReaderValue", BindingFlags.Static | BindingFlags.NonPublic); + internal static MethodInfo MethodExecuteArrayRowReadClassOrTuple = typeof(Utils).GetMethod("ExecuteArrayRowReadClassOrTuple", BindingFlags.Static | BindingFlags.NonPublic); + internal static MethodInfo MethodGetDataReaderValue = typeof(Utils).GetMethod("GetDataReaderValue", BindingFlags.Static | BindingFlags.NonPublic); - static ConcurrentDictionary> _dicFillPropertyValue = new ConcurrentDictionary>(); - internal static void FillPropertyValue(object info, string memberAccessPath, object value) { - var typeObj = info.GetType(); - var typeValue = value.GetType(); - var key = "FillPropertyValue_" + typeObj.FullName + "_" + typeValue.FullName; - var act = _dicFillPropertyValue.GetOrAdd($"{key}.{memberAccessPath}", s => { - var parmInfo = Expression.Parameter(typeof(object), "info"); - var parmValue = Expression.Parameter(typeof(object), "value"); - Expression exp = Expression.Convert(parmInfo, typeObj); - foreach (var pro in memberAccessPath.Split('.')) - exp = Expression.PropertyOrField(exp, pro) ?? throw new Exception(string.Concat(exp.Type.FullName, " 没有定义属性 ", pro)); + static ConcurrentDictionary> _dicFillPropertyValue = new ConcurrentDictionary>(); + internal static void FillPropertyValue(object info, string memberAccessPath, object value) + { + var typeObj = info.GetType(); + var typeValue = value.GetType(); + var key = "FillPropertyValue_" + typeObj.FullName + "_" + typeValue.FullName; + var act = _dicFillPropertyValue.GetOrAdd($"{key}.{memberAccessPath}", s => + { + var parmInfo = Expression.Parameter(typeof(object), "info"); + var parmValue = Expression.Parameter(typeof(object), "value"); + Expression exp = Expression.Convert(parmInfo, typeObj); + foreach (var pro in memberAccessPath.Split('.')) + exp = Expression.PropertyOrField(exp, pro) ?? throw new Exception(string.Concat(exp.Type.FullName, " 没有定义属性 ", pro)); - var value2 = Expression.Call(MethodGetDataReaderValue, Expression.Constant(exp.Type), parmValue); - var value3 = Expression.Convert(parmValue, typeValue); - exp = Expression.Assign(exp, value3); - return Expression.Lambda>(exp, parmInfo, parmValue).Compile(); - }); - act(info, value); - } + var value2 = Expression.Call(MethodGetDataReaderValue, Expression.Constant(exp.Type), parmValue); + var value3 = Expression.Convert(parmValue, typeValue); + exp = Expression.Assign(exp, value3); + return Expression.Lambda>(exp, parmInfo, parmValue).Compile(); + }); + act(info, value); + } - static BigInteger ToBigInteger(string that) { - if (string.IsNullOrEmpty(that)) return 0; - if (BigInteger.TryParse(that, System.Globalization.NumberStyles.Any, null, out var trybigint)) return trybigint; - return 0; - } - static string ToStringConcat(object obj) { - if (obj == null) return null; - return string.Concat(obj); - } + static BigInteger ToBigInteger(string that) + { + if (string.IsNullOrEmpty(that)) return 0; + if (BigInteger.TryParse(that, System.Globalization.NumberStyles.Any, null, out var trybigint)) return trybigint; + return 0; + } + static string ToStringConcat(object obj) + { + if (obj == null) return null; + return string.Concat(obj); + } - static ConcurrentDictionary>> _dicGetDataReaderValue = new ConcurrentDictionary>>(); - static MethodInfo MethodArrayGetValue = typeof(Array).GetMethod("GetValue", new[] { typeof(int) }); - static MethodInfo MethodArrayGetLength = typeof(Array).GetMethod("GetLength", new[] { typeof(int) }); - static MethodInfo MethodGuidTryParse = typeof(Guid).GetMethod("TryParse", new[] { typeof(string), typeof(Guid).MakeByRefType() }); - static MethodInfo MethodEnumParse = typeof(Enum).GetMethod("Parse", new[] { typeof(Type), typeof(string), typeof(bool) }); - static MethodInfo MethodConvertChangeType = typeof(Convert).GetMethod("ChangeType", new[] { typeof(object), typeof(Type) }); - static MethodInfo MethodTimeSpanFromSeconds = typeof(TimeSpan).GetMethod("FromSeconds"); - static MethodInfo MethodSByteTryParse = typeof(sbyte).GetMethod("TryParse", new[] { typeof(string), typeof(sbyte).MakeByRefType() }); - static MethodInfo MethodShortTryParse = typeof(short).GetMethod("TryParse", new[] { typeof(string), typeof(short).MakeByRefType() }); - static MethodInfo MethodIntTryParse = typeof(int).GetMethod("TryParse", new[] { typeof(string), typeof(int).MakeByRefType() }); - static MethodInfo MethodLongTryParse = typeof(long).GetMethod("TryParse", new[] { typeof(string), typeof(long).MakeByRefType() }); - static MethodInfo MethodByteTryParse = typeof(byte).GetMethod("TryParse", new[] { typeof(string), typeof(byte).MakeByRefType() }); - static MethodInfo MethodUShortTryParse = typeof(ushort).GetMethod("TryParse", new[] { typeof(string), typeof(ushort).MakeByRefType() }); - static MethodInfo MethodUIntTryParse = typeof(uint).GetMethod("TryParse", new[] { typeof(string), typeof(uint).MakeByRefType() }); - static MethodInfo MethodULongTryParse = typeof(ulong).GetMethod("TryParse", new[] { typeof(string), typeof(ulong).MakeByRefType() }); - static MethodInfo MethodDoubleTryParse = typeof(double).GetMethod("TryParse", new[] { typeof(string), typeof(double).MakeByRefType() }); - static MethodInfo MethodFloatTryParse = typeof(float).GetMethod("TryParse", new[] { typeof(string), typeof(float).MakeByRefType() }); - static MethodInfo MethodDecimalTryParse = typeof(decimal).GetMethod("TryParse", new[] { typeof(string), typeof(decimal).MakeByRefType() }); - static MethodInfo MethodTimeSpanTryParse = typeof(TimeSpan).GetMethod("TryParse", new[] { typeof(string), typeof(TimeSpan).MakeByRefType() }); - static MethodInfo MethodDateTimeTryParse = typeof(DateTime).GetMethod("TryParse", new[] { typeof(string), typeof(DateTime).MakeByRefType() }); - static MethodInfo MethodDateTimeOffsetTryParse = typeof(DateTimeOffset).GetMethod("TryParse", new[] { typeof(string), typeof(DateTimeOffset).MakeByRefType() }); - static MethodInfo MethodToString = typeof(Utils).GetMethod("ToStringConcat", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(object) }, null); - static MethodInfo MethodBigIntegerParse = typeof(Utils).GetMethod("ToBigInteger", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(string) }, null); + static ConcurrentDictionary>> _dicGetDataReaderValue = new ConcurrentDictionary>>(); + static MethodInfo MethodArrayGetValue = typeof(Array).GetMethod("GetValue", new[] { typeof(int) }); + static MethodInfo MethodArrayGetLength = typeof(Array).GetMethod("GetLength", new[] { typeof(int) }); + static MethodInfo MethodGuidTryParse = typeof(Guid).GetMethod("TryParse", new[] { typeof(string), typeof(Guid).MakeByRefType() }); + static MethodInfo MethodEnumParse = typeof(Enum).GetMethod("Parse", new[] { typeof(Type), typeof(string), typeof(bool) }); + static MethodInfo MethodConvertChangeType = typeof(Convert).GetMethod("ChangeType", new[] { typeof(object), typeof(Type) }); + static MethodInfo MethodTimeSpanFromSeconds = typeof(TimeSpan).GetMethod("FromSeconds"); + static MethodInfo MethodSByteTryParse = typeof(sbyte).GetMethod("TryParse", new[] { typeof(string), typeof(sbyte).MakeByRefType() }); + static MethodInfo MethodShortTryParse = typeof(short).GetMethod("TryParse", new[] { typeof(string), typeof(short).MakeByRefType() }); + static MethodInfo MethodIntTryParse = typeof(int).GetMethod("TryParse", new[] { typeof(string), typeof(int).MakeByRefType() }); + static MethodInfo MethodLongTryParse = typeof(long).GetMethod("TryParse", new[] { typeof(string), typeof(long).MakeByRefType() }); + static MethodInfo MethodByteTryParse = typeof(byte).GetMethod("TryParse", new[] { typeof(string), typeof(byte).MakeByRefType() }); + static MethodInfo MethodUShortTryParse = typeof(ushort).GetMethod("TryParse", new[] { typeof(string), typeof(ushort).MakeByRefType() }); + static MethodInfo MethodUIntTryParse = typeof(uint).GetMethod("TryParse", new[] { typeof(string), typeof(uint).MakeByRefType() }); + static MethodInfo MethodULongTryParse = typeof(ulong).GetMethod("TryParse", new[] { typeof(string), typeof(ulong).MakeByRefType() }); + static MethodInfo MethodDoubleTryParse = typeof(double).GetMethod("TryParse", new[] { typeof(string), typeof(double).MakeByRefType() }); + static MethodInfo MethodFloatTryParse = typeof(float).GetMethod("TryParse", new[] { typeof(string), typeof(float).MakeByRefType() }); + static MethodInfo MethodDecimalTryParse = typeof(decimal).GetMethod("TryParse", new[] { typeof(string), typeof(decimal).MakeByRefType() }); + static MethodInfo MethodTimeSpanTryParse = typeof(TimeSpan).GetMethod("TryParse", new[] { typeof(string), typeof(TimeSpan).MakeByRefType() }); + static MethodInfo MethodDateTimeTryParse = typeof(DateTime).GetMethod("TryParse", new[] { typeof(string), typeof(DateTime).MakeByRefType() }); + static MethodInfo MethodDateTimeOffsetTryParse = typeof(DateTimeOffset).GetMethod("TryParse", new[] { typeof(string), typeof(DateTimeOffset).MakeByRefType() }); + static MethodInfo MethodToString = typeof(Utils).GetMethod("ToStringConcat", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(object) }, null); + static MethodInfo MethodBigIntegerParse = typeof(Utils).GetMethod("ToBigInteger", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(string) }, null); - public static ConcurrentBag> GetDataReaderValueBlockExpressionSwitchTypeFullName = new ConcurrentBag>(); - public static Expression GetDataReaderValueBlockExpression(Type type, Expression value) { - var returnTarget = Expression.Label(typeof(object)); - var valueExp = Expression.Variable(typeof(object), "locvalue"); - Func funcGetExpression = () => { - if (type.FullName == "System.Byte[]") return Expression.Return(returnTarget, valueExp); - if (type.IsArray) { - var elementType = type.GetElementType(); - var arrNewExp = Expression.Variable(type, "arrNew"); - var arrExp = Expression.Variable(typeof(Array), "arr"); - var arrLenExp = Expression.Variable(typeof(int), "arrLen"); - var arrXExp = Expression.Variable(typeof(int), "arrX"); - var arrReadValExp = Expression.Variable(typeof(object), "arrReadVal"); - var label = Expression.Label(typeof(int)); - return Expression.IfThenElse( - Expression.TypeEqual(valueExp, type), - Expression.Return(returnTarget, valueExp), - Expression.Block( - new[] { arrNewExp, arrExp, arrLenExp, arrXExp, arrReadValExp }, - Expression.Assign(arrExp, Expression.TypeAs(valueExp, typeof(Array))), - Expression.Assign(arrLenExp, Expression.Call(arrExp, MethodArrayGetLength, Expression.Constant(0))), - Expression.Assign(arrXExp, Expression.Constant(0)), - Expression.Assign(arrNewExp, Expression.NewArrayBounds(elementType, arrLenExp)), - Expression.Loop( - Expression.IfThenElse( - Expression.LessThan(arrXExp, arrLenExp), - Expression.Block( - Expression.Assign(arrReadValExp, GetDataReaderValueBlockExpression(elementType, Expression.Call(arrExp, MethodArrayGetValue, arrXExp))), - Expression.IfThenElse( - Expression.Equal(arrReadValExp, Expression.Constant(null)), - Expression.Assign(Expression.ArrayAccess(arrNewExp, arrXExp), Expression.Default(elementType)), - Expression.Assign(Expression.ArrayAccess(arrNewExp, arrXExp), Expression.Convert(arrReadValExp, elementType)) - ), - Expression.PostIncrementAssign(arrXExp) - ), - Expression.Break(label, arrXExp) - ), - label - ), - Expression.Return(returnTarget, arrNewExp) - ) - ); - } - var typeOrg = type; - if (type.IsNullableType()) type = type.GenericTypeArguments.First(); - if (type.IsEnum) - return Expression.Block( - Expression.IfThenElse( - Expression.Equal(Expression.TypeAs(valueExp, typeof(string)), Expression.Constant(string.Empty)), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(type), typeof(object))), - Expression.Return(returnTarget, Expression.Call(MethodEnumParse, Expression.Constant(type, typeof(Type)), Expression.Call(MethodToString, valueExp), Expression.Constant(true, typeof(bool)))) - ) - ); - Expression tryparseExp = null; - Expression tryparseBooleanExp = null; - ParameterExpression tryparseVarExp = null; - switch (type.FullName) { - case "System.Guid": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(Guid)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodGuidTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Numerics.BigInteger": return Expression.Return(returnTarget, Expression.Convert(Expression.Call(MethodBigIntegerParse, Expression.Call(MethodToString, valueExp)), typeof(object))); - case "System.TimeSpan": - ParameterExpression tryparseVarTsExp, valueStrExp; - return Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(double)), tryparseVarTsExp = Expression.Variable(typeof(TimeSpan)), valueStrExp = Expression.Variable(typeof(string)) }, - new Expression[] { - Expression.Assign(valueStrExp, Expression.Call(MethodToString, valueExp)), - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodDoubleTryParse, valueStrExp, tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(Expression.Call(MethodTimeSpanFromSeconds, tryparseVarExp), typeof(object))), - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodTimeSpanTryParse, valueStrExp, tryparseVarTsExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarTsExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - ) - } - ); - case "System.SByte": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(sbyte)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodSByteTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Int16": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(short)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodShortTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Int32": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(int)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodIntTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Int64": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(long)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodLongTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Byte": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(byte)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodByteTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.UInt16": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(ushort)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodUShortTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.UInt32": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(uint)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodUIntTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.UInt64": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(ulong)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodULongTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Single": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(float)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodFloatTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Double": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(double)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodDoubleTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Decimal": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(decimal)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodDecimalTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.DateTime": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(DateTime)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodDateTimeTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.DateTimeOffset": - tryparseExp = Expression.Block( - new[] { tryparseVarExp = Expression.Variable(typeof(DateTimeOffset)) }, - new Expression[] { - Expression.IfThenElse( - Expression.IsTrue(Expression.Call(MethodDateTimeOffsetTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), - Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) - ) - } - ); - break; - case "System.Boolean": - tryparseBooleanExp = Expression.Return(returnTarget, - Expression.Convert( - Expression.Not( - Expression.Or( - Expression.Equal(Expression.Convert(valueExp, typeof(string)), Expression.Constant("False")), - Expression.Or( - Expression.Equal(Expression.Convert(valueExp, typeof(string)), Expression.Constant("false")), - Expression.Equal(Expression.Convert(valueExp, typeof(string)), Expression.Constant("0"))))), - typeof(object)) - ); - break; - default: - foreach (var switchFunc in GetDataReaderValueBlockExpressionSwitchTypeFullName) { - var switchFuncRet = switchFunc(returnTarget, valueExp, type.FullName); - if (switchFuncRet != null) return switchFuncRet; - } - break; - } - Expression switchExp = null; - if (tryparseExp != null) - switchExp = Expression.Switch( - Expression.Constant(type), - Expression.SwitchCase(tryparseExp, - Expression.Constant(typeof(Guid)), - Expression.Constant(typeof(sbyte)), Expression.Constant(typeof(short)), Expression.Constant(typeof(int)), Expression.Constant(typeof(long)), - Expression.Constant(typeof(byte)), Expression.Constant(typeof(ushort)), Expression.Constant(typeof(uint)), Expression.Constant(typeof(ulong)), - Expression.Constant(typeof(double)), Expression.Constant(typeof(float)), Expression.Constant(typeof(decimal)), - Expression.Constant(typeof(DateTime)), Expression.Constant(typeof(DateTimeOffset)) - ), - Expression.SwitchCase(Expression.Return(returnTarget, Expression.Call(MethodConvertChangeType, valueExp, Expression.Constant(type, typeof(Type)))), Expression.Constant(type)) - ); - else if (tryparseBooleanExp != null) - switchExp = Expression.Switch( - Expression.Constant(type), - Expression.SwitchCase(tryparseBooleanExp, Expression.Constant(typeof(bool))), - Expression.SwitchCase(Expression.Return(returnTarget, Expression.Call(MethodConvertChangeType, valueExp, Expression.Constant(type, typeof(Type)))), Expression.Constant(type)) - ); - else if (type == typeof(string)) - switchExp = Expression.Return(returnTarget, Expression.Convert(Expression.Call(MethodToString, valueExp), typeof(object))); - else - switchExp = Expression.Return(returnTarget, Expression.Call(MethodConvertChangeType, valueExp, Expression.Constant(type, typeof(Type)))); + public static ConcurrentBag> GetDataReaderValueBlockExpressionSwitchTypeFullName = new ConcurrentBag>(); + public static Expression GetDataReaderValueBlockExpression(Type type, Expression value) + { + var returnTarget = Expression.Label(typeof(object)); + var valueExp = Expression.Variable(typeof(object), "locvalue"); + Func funcGetExpression = () => + { + if (type.FullName == "System.Byte[]") return Expression.Return(returnTarget, valueExp); + if (type.IsArray) + { + var elementType = type.GetElementType(); + var arrNewExp = Expression.Variable(type, "arrNew"); + var arrExp = Expression.Variable(typeof(Array), "arr"); + var arrLenExp = Expression.Variable(typeof(int), "arrLen"); + var arrXExp = Expression.Variable(typeof(int), "arrX"); + var arrReadValExp = Expression.Variable(typeof(object), "arrReadVal"); + var label = Expression.Label(typeof(int)); + return Expression.IfThenElse( + Expression.TypeEqual(valueExp, type), + Expression.Return(returnTarget, valueExp), + Expression.Block( + new[] { arrNewExp, arrExp, arrLenExp, arrXExp, arrReadValExp }, + Expression.Assign(arrExp, Expression.TypeAs(valueExp, typeof(Array))), + Expression.Assign(arrLenExp, Expression.Call(arrExp, MethodArrayGetLength, Expression.Constant(0))), + Expression.Assign(arrXExp, Expression.Constant(0)), + Expression.Assign(arrNewExp, Expression.NewArrayBounds(elementType, arrLenExp)), + Expression.Loop( + Expression.IfThenElse( + Expression.LessThan(arrXExp, arrLenExp), + Expression.Block( + Expression.Assign(arrReadValExp, GetDataReaderValueBlockExpression(elementType, Expression.Call(arrExp, MethodArrayGetValue, arrXExp))), + Expression.IfThenElse( + Expression.Equal(arrReadValExp, Expression.Constant(null)), + Expression.Assign(Expression.ArrayAccess(arrNewExp, arrXExp), Expression.Default(elementType)), + Expression.Assign(Expression.ArrayAccess(arrNewExp, arrXExp), Expression.Convert(arrReadValExp, elementType)) + ), + Expression.PostIncrementAssign(arrXExp) + ), + Expression.Break(label, arrXExp) + ), + label + ), + Expression.Return(returnTarget, arrNewExp) + ) + ); + } + var typeOrg = type; + if (type.IsNullableType()) type = type.GenericTypeArguments.First(); + if (type.IsEnum) + return Expression.Block( + Expression.IfThenElse( + Expression.Equal(Expression.TypeAs(valueExp, typeof(string)), Expression.Constant(string.Empty)), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(type), typeof(object))), + Expression.Return(returnTarget, Expression.Call(MethodEnumParse, Expression.Constant(type, typeof(Type)), Expression.Call(MethodToString, valueExp), Expression.Constant(true, typeof(bool)))) + ) + ); + Expression tryparseExp = null; + Expression tryparseBooleanExp = null; + ParameterExpression tryparseVarExp = null; + switch (type.FullName) + { + case "System.Guid": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(Guid)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodGuidTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Numerics.BigInteger": return Expression.Return(returnTarget, Expression.Convert(Expression.Call(MethodBigIntegerParse, Expression.Call(MethodToString, valueExp)), typeof(object))); + case "System.TimeSpan": + ParameterExpression tryparseVarTsExp, valueStrExp; + return Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(double)), tryparseVarTsExp = Expression.Variable(typeof(TimeSpan)), valueStrExp = Expression.Variable(typeof(string)) }, + new Expression[] { + Expression.Assign(valueStrExp, Expression.Call(MethodToString, valueExp)), + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodDoubleTryParse, valueStrExp, tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(Expression.Call(MethodTimeSpanFromSeconds, tryparseVarExp), typeof(object))), + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodTimeSpanTryParse, valueStrExp, tryparseVarTsExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarTsExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + ) + } + ); + case "System.SByte": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(sbyte)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodSByteTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Int16": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(short)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodShortTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Int32": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(int)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodIntTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Int64": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(long)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodLongTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Byte": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(byte)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodByteTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.UInt16": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(ushort)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodUShortTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.UInt32": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(uint)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodUIntTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.UInt64": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(ulong)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodULongTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Single": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(float)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodFloatTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Double": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(double)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodDoubleTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Decimal": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(decimal)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodDecimalTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.DateTime": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(DateTime)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodDateTimeTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.DateTimeOffset": + tryparseExp = Expression.Block( + new[] { tryparseVarExp = Expression.Variable(typeof(DateTimeOffset)) }, + new Expression[] { + Expression.IfThenElse( + Expression.IsTrue(Expression.Call(MethodDateTimeOffsetTryParse, Expression.Convert(valueExp, typeof(string)), tryparseVarExp)), + Expression.Return(returnTarget, Expression.Convert(tryparseVarExp, typeof(object))), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(typeOrg), typeof(object))) + ) + } + ); + break; + case "System.Boolean": + tryparseBooleanExp = Expression.Return(returnTarget, + Expression.Convert( + Expression.Not( + Expression.Or( + Expression.Equal(Expression.Convert(valueExp, typeof(string)), Expression.Constant("False")), + Expression.Or( + Expression.Equal(Expression.Convert(valueExp, typeof(string)), Expression.Constant("false")), + Expression.Equal(Expression.Convert(valueExp, typeof(string)), Expression.Constant("0"))))), + typeof(object)) + ); + break; + default: + foreach (var switchFunc in GetDataReaderValueBlockExpressionSwitchTypeFullName) + { + var switchFuncRet = switchFunc(returnTarget, valueExp, type.FullName); + if (switchFuncRet != null) return switchFuncRet; + } + break; + } + Expression switchExp = null; + if (tryparseExp != null) + switchExp = Expression.Switch( + Expression.Constant(type), + Expression.SwitchCase(tryparseExp, + Expression.Constant(typeof(Guid)), + Expression.Constant(typeof(sbyte)), Expression.Constant(typeof(short)), Expression.Constant(typeof(int)), Expression.Constant(typeof(long)), + Expression.Constant(typeof(byte)), Expression.Constant(typeof(ushort)), Expression.Constant(typeof(uint)), Expression.Constant(typeof(ulong)), + Expression.Constant(typeof(double)), Expression.Constant(typeof(float)), Expression.Constant(typeof(decimal)), + Expression.Constant(typeof(DateTime)), Expression.Constant(typeof(DateTimeOffset)) + ), + Expression.SwitchCase(Expression.Return(returnTarget, Expression.Call(MethodConvertChangeType, valueExp, Expression.Constant(type, typeof(Type)))), Expression.Constant(type)) + ); + else if (tryparseBooleanExp != null) + switchExp = Expression.Switch( + Expression.Constant(type), + Expression.SwitchCase(tryparseBooleanExp, Expression.Constant(typeof(bool))), + Expression.SwitchCase(Expression.Return(returnTarget, Expression.Call(MethodConvertChangeType, valueExp, Expression.Constant(type, typeof(Type)))), Expression.Constant(type)) + ); + else if (type == typeof(string)) + switchExp = Expression.Return(returnTarget, Expression.Convert(Expression.Call(MethodToString, valueExp), typeof(object))); + else + switchExp = Expression.Return(returnTarget, Expression.Call(MethodConvertChangeType, valueExp, Expression.Constant(type, typeof(Type)))); - var defaultRetExp = type == typeof(string) ? - Expression.Return(returnTarget, Expression.Convert(Expression.Call(MethodToString, valueExp), typeof(object))) : - Expression.Return(returnTarget, Expression.Call(MethodConvertChangeType, valueExp, Expression.Constant(type, typeof(Type)))); + var defaultRetExp = type == typeof(string) ? + Expression.Return(returnTarget, Expression.Convert(Expression.Call(MethodToString, valueExp), typeof(object))) : + Expression.Return(returnTarget, Expression.Call(MethodConvertChangeType, valueExp, Expression.Constant(type, typeof(Type)))); - return Expression.IfThenElse( - Expression.TypeEqual(valueExp, type), - Expression.Return(returnTarget, valueExp), - Expression.IfThenElse( - Expression.TypeEqual(valueExp, typeof(string)), - switchExp, - defaultRetExp - ) - ); - }; + return Expression.IfThenElse( + Expression.TypeEqual(valueExp, type), + Expression.Return(returnTarget, valueExp), + Expression.IfThenElse( + Expression.TypeEqual(valueExp, typeof(string)), + switchExp, + defaultRetExp + ) + ); + }; - return Expression.Block( - new[] { valueExp }, - Expression.Assign(valueExp, Expression.Convert(value, typeof(object))), - Expression.IfThenElse( - Expression.Or( - Expression.Equal(valueExp, Expression.Constant(null)), - Expression.Equal(valueExp, Expression.Constant(DBNull.Value)) - ), - Expression.Return(returnTarget, Expression.Convert(Expression.Default(type), typeof(object))), - funcGetExpression() - ), - Expression.Label(returnTarget, Expression.Default(typeof(object))) - ); - } - public static object GetDataReaderValue(Type type, object value) { - //if (value == null || value == DBNull.Value) return Activator.CreateInstance(type); - if (type == null) return value; - var func = _dicGetDataReaderValue.GetOrAdd(type, k1 => new ConcurrentDictionary>()).GetOrAdd(value?.GetType() ?? type, valueType => { - var parmExp = Expression.Parameter(typeof(object), "value"); - var exp = GetDataReaderValueBlockExpression(type, parmExp); - return Expression.Lambda>(exp, parmExp).Compile(); - }); - return func(value); - } - public static string GetCsName(string name) { - name = Regex.Replace(name.TrimStart('@'), @"[^\w]", "_"); - return char.IsLetter(name, 0) ? name : string.Concat("_", name); - } - } + return Expression.Block( + new[] { valueExp }, + Expression.Assign(valueExp, Expression.Convert(value, typeof(object))), + Expression.IfThenElse( + Expression.Or( + Expression.Equal(valueExp, Expression.Constant(null)), + Expression.Equal(valueExp, Expression.Constant(DBNull.Value)) + ), + Expression.Return(returnTarget, Expression.Convert(Expression.Default(type), typeof(object))), + funcGetExpression() + ), + Expression.Label(returnTarget, Expression.Default(typeof(object))) + ); + } + public static object GetDataReaderValue(Type type, object value) + { + //if (value == null || value == DBNull.Value) return Activator.CreateInstance(type); + if (type == null) return value; + var func = _dicGetDataReaderValue.GetOrAdd(type, k1 => new ConcurrentDictionary>()).GetOrAdd(value?.GetType() ?? type, valueType => + { + var parmExp = Expression.Parameter(typeof(object), "value"); + var exp = GetDataReaderValueBlockExpression(type, parmExp); + return Expression.Lambda>(exp, parmExp).Compile(); + }); + return func(value); + } + public static string GetCsName(string name) + { + name = Regex.Replace(name.TrimStart('@'), @"[^\w]", "_"); + return char.IsLetter(name, 0) ? name : string.Concat("_", name); + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.MySql/Curd/MySqlDelete.cs b/Providers/FreeSql.Provider.MySql/Curd/MySqlDelete.cs index db2eaa24..2b63f5b6 100644 --- a/Providers/FreeSql.Provider.MySql/Curd/MySqlDelete.cs +++ b/Providers/FreeSql.Provider.MySql/Curd/MySqlDelete.cs @@ -5,74 +5,91 @@ using System.Data; using System.Text; using System.Threading.Tasks; -namespace FreeSql.MySql.Curd { +namespace FreeSql.MySql.Curd +{ - class MySqlDelete : Internal.CommonProvider.DeleteProvider where T1 : class { - public MySqlDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + class MySqlDelete : Internal.CommonProvider.DeleteProvider where T1 : class + { + public MySqlDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override List ExecuteDeleted() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + public override List ExecuteDeleted() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async public override Task> ExecuteDeletedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async public override Task> ExecuteDeletedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - } + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + } } diff --git a/Providers/FreeSql.Provider.MySql/Curd/MySqlInsert.cs b/Providers/FreeSql.Provider.MySql/Curd/MySqlInsert.cs index 0371246f..35747893 100644 --- a/Providers/FreeSql.Provider.MySql/Curd/MySqlInsert.cs +++ b/Providers/FreeSql.Provider.MySql/Curd/MySqlInsert.cs @@ -5,122 +5,151 @@ using System.Data; using System.Text; using System.Threading.Tasks; -namespace FreeSql.MySql.Curd { +namespace FreeSql.MySql.Curd +{ - class MySqlInsert : Internal.CommonProvider.InsertProvider where T1 : class { - public MySqlInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) - : base(orm, commonUtils, commonExpression) { - } + class MySqlInsert : Internal.CommonProvider.InsertProvider where T1 : class + { + public MySqlInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + : base(orm, commonUtils, commonExpression) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(5000, 3000); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(5000, 3000); - public override long ExecuteIdentity() => base.SplitExecuteIdentity(5000, 3000); - public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(5000, 3000); - public override List ExecuteInserted() => base.SplitExecuteInserted(5000, 3000); - public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(5000, 3000); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(5000, 3000); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(5000, 3000); + public override long ExecuteIdentity() => base.SplitExecuteIdentity(5000, 3000); + public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(5000, 3000); + public override List ExecuteInserted() => base.SplitExecuteInserted(5000, 3000); + public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(5000, 3000); - protected override long RawExecuteIdentity() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + protected override long RawExecuteIdentity() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - sql = string.Concat(sql, "; SELECT LAST_INSERT_ID();"); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - long ret = 0; - Exception exception = null; - try { - ret = long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out var trylng) ? trylng : 0; - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task RawExecuteIdentityAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + sql = string.Concat(sql, "; SELECT LAST_INSERT_ID();"); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + long ret = 0; + Exception exception = null; + try + { + ret = long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out var trylng) ? trylng : 0; + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task RawExecuteIdentityAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - sql = string.Concat(sql, "; SELECT LAST_INSERT_ID();"); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - long ret = 0; - Exception exception = null; - try { - ret = long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out var trylng) ? trylng : 0; - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - protected override List RawExecuteInserted() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + sql = string.Concat(sql, "; SELECT LAST_INSERT_ID();"); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + long ret = 0; + Exception exception = null; + try + { + ret = long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out var trylng) ? trylng : 0; + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + protected override List RawExecuteInserted() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task> RawExecuteInsertedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task> RawExecuteInsertedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - } + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + } } diff --git a/Providers/FreeSql.Provider.MySql/Curd/MySqlSelect.cs b/Providers/FreeSql.Provider.MySql/Curd/MySqlSelect.cs index 2a856b34..f9463f3d 100644 --- a/Providers/FreeSql.Provider.MySql/Curd/MySqlSelect.cs +++ b/Providers/FreeSql.Provider.MySql/Curd/MySqlSelect.cs @@ -6,123 +6,145 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.MySql.Curd { +namespace FreeSql.MySql.Curd +{ - class MySqlSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class { + class MySqlSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class + { - internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) { - if (_orm.CodeFirst.IsAutoSyncStructure) - _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); + internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) + { + if (_orm.CodeFirst.IsAutoSyncStructure) + _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); - var sb = new StringBuilder(); - var sbnav = new StringBuilder(); - sb.Append(_select); - if (_distinct) sb.Append("DISTINCT "); - sb.Append(field).Append(" \r\nFROM "); - var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); - var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); - for (var a = 0; a < tbsfrom.Length; a++) { - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); - if (tbsjoin.Length > 0) { - //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 - for (var b = 1; b < tbsfrom.Length; b++) { - sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); - if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); - else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); - } - break; - } else { - if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); - if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); - } - if (a < tbsfrom.Length - 1) sb.Append(", "); - } - foreach (var tb in tbsjoin) { - if (tb.Type == SelectTableInfoType.Parent) continue; - switch (tb.Type) { - case SelectTableInfoType.LeftJoin: - sb.Append(" \r\nLEFT JOIN "); - break; - case SelectTableInfoType.InnerJoin: - sb.Append(" \r\nINNER JOIN "); - break; - case SelectTableInfoType.RightJoin: - sb.Append(" \r\nRIGHT JOIN "); - break; - } - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); - if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); - } - if (_join.Length > 0) sb.Append(_join); + var sb = new StringBuilder(); + var sbnav = new StringBuilder(); + sb.Append(_select); + if (_distinct) sb.Append("DISTINCT "); + sb.Append(field).Append(" \r\nFROM "); + var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); + var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); + for (var a = 0; a < tbsfrom.Length; a++) + { + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); + if (tbsjoin.Length > 0) + { + //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 + for (var b = 1; b < tbsfrom.Length; b++) + { + sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); + if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); + else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); + } + break; + } + else + { + if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); + if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); + } + if (a < tbsfrom.Length - 1) sb.Append(", "); + } + foreach (var tb in tbsjoin) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + switch (tb.Type) + { + case SelectTableInfoType.LeftJoin: + sb.Append(" \r\nLEFT JOIN "); + break; + case SelectTableInfoType.InnerJoin: + sb.Append(" \r\nINNER JOIN "); + break; + case SelectTableInfoType.RightJoin: + sb.Append(" \r\nRIGHT JOIN "); + break; + } + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); + if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); + } + if (_join.Length > 0) sb.Append(_join); - sbnav.Append(_where); - foreach (var tb in _tables) { - if (tb.Type == SelectTableInfoType.Parent) continue; - if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) - sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); - } - if (sbnav.Length > 0) { - sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); - } - if (string.IsNullOrEmpty(_groupby) == false) { - sb.Append(_groupby); - if (string.IsNullOrEmpty(_having) == false) - sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); - } - sb.Append(_orderby); - if (_skip > 0 || _limit > 0) - sb.Append(" \r\nlimit ").Append(Math.Max(0, _skip)).Append(",").Append(_limit > 0 ? _limit : -1); + sbnav.Append(_where); + foreach (var tb in _tables) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) + sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); + } + if (sbnav.Length > 0) + { + sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); + } + if (string.IsNullOrEmpty(_groupby) == false) + { + sb.Append(_groupby); + if (string.IsNullOrEmpty(_having) == false) + sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); + } + sb.Append(_orderby); + if (_skip > 0 || _limit > 0) + sb.Append(" \r\nlimit ").Append(Math.Max(0, _skip)).Append(",").Append(_limit > 0 ? _limit : -1); - sbnav.Clear(); - return sb.ToString(); - } + sbnav.Clear(); + return sb.ToString(); + } - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class MySqlSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class { - public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new MySqlSelect(_orm, _commonUtils, _commonExpression, null); MySqlSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class MySqlSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class + { + public MySqlSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => MySqlSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } } diff --git a/Providers/FreeSql.Provider.MySql/Curd/MySqlUpdate.cs b/Providers/FreeSql.Provider.MySql/Curd/MySqlUpdate.cs index 2b227538..3015a0e3 100644 --- a/Providers/FreeSql.Provider.MySql/Curd/MySqlUpdate.cs +++ b/Providers/FreeSql.Provider.MySql/Curd/MySqlUpdate.cs @@ -7,113 +7,136 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.MySql.Curd { +namespace FreeSql.MySql.Curd +{ - class MySqlUpdate : Internal.CommonProvider.UpdateProvider where T1 : class { + class MySqlUpdate : Internal.CommonProvider.UpdateProvider where T1 : class + { - public MySqlUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + public MySqlUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 3000); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 3000); - public override List ExecuteUpdated() => base.SplitExecuteUpdated(500, 3000); - public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(500, 3000); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 3000); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 3000); + public override List ExecuteUpdated() => base.SplitExecuteUpdated(500, 3000); + public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(500, 3000); - protected override List RawExecuteUpdated() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + protected override List RawExecuteUpdated() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var dbParms = _params.Concat(_paramsSource).ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); - ValidateVersionAndThrow(ret.Count); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task> RawExecuteUpdatedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var dbParms = _params.Concat(_paramsSource).ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); + ValidateVersionAndThrow(ret.Count); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task> RawExecuteUpdatedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var dbParms = _params.Concat(_paramsSource).ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - ValidateVersionAndThrow(ret.Count); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var dbParms = _params.Concat(_paramsSource).ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + ValidateVersionAndThrow(ret.Count); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } - protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) { - if (_table.Primarys.Length == 1) { - caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); - return; - } - caseWhen.Append("CONCAT("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) caseWhen.Append(", "); - caseWhen.Append(_commonUtils.QuoteReadColumn(pk.Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))); - ++pkidx; - } - caseWhen.Append(")"); - } + protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) + { + if (_table.Primarys.Length == 1) + { + caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); + return; + } + caseWhen.Append("CONCAT("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) caseWhen.Append(", "); + caseWhen.Append(_commonUtils.QuoteReadColumn(pk.Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))); + ++pkidx; + } + caseWhen.Append(")"); + } - protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) { - if (_table.Primarys.Length == 1) { - sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); - return; - } - sb.Append("CONCAT("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) sb.Append(", "); - sb.Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))); - ++pkidx; - } - sb.Append(")"); - } - } + protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) + { + if (_table.Primarys.Length == 1) + { + sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); + return; + } + sb.Append("CONCAT("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) sb.Append(", "); + sb.Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))); + ++pkidx; + } + sb.Append(")"); + } + } } diff --git a/Providers/FreeSql.Provider.MySql/MySqlAdo/MySqlAdo.cs b/Providers/FreeSql.Provider.MySql/MySqlAdo/MySqlAdo.cs index c04aa5ca..3e0154ac 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlAdo/MySqlAdo.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlAdo/MySqlAdo.cs @@ -7,57 +7,66 @@ using System.Data.Common; using System.Text; using System.Threading; -namespace FreeSql.MySql { - class MySqlAdo : FreeSql.Internal.CommonProvider.AdoProvider { +namespace FreeSql.MySql +{ + class MySqlAdo : FreeSql.Internal.CommonProvider.AdoProvider + { - public MySqlAdo() : base(DataType.MySql) { } - public MySqlAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.MySql) { - base._util = util; - if (!string.IsNullOrEmpty(masterConnectionString)) - MasterPool = new MySqlConnectionPool("主库", masterConnectionString, null, null); - if (slaveConnectionStrings != null) { - foreach (var slaveConnectionString in slaveConnectionStrings) { - var slavePool = new MySqlConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); - SlavePools.Add(slavePool); - } - } - } - static DateTime dt1970 = new DateTime(1970, 1, 1); - public override object AddslashesProcessParam(object param, Type mapType) { - if (param == null) return "NULL"; - if (mapType != null && mapType != param.GetType()) - param = Utils.GetDataReaderValue(mapType, param); - if (param is bool || param is bool?) - return (bool)param ? 1 : 0; - else if (param is string || param is char) - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - else if (param is Enum) - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); //((Enum)val).ToInt64(); - else if (decimal.TryParse(string.Concat(param), out var trydec)) - return param; - else if (param is DateTime || param is DateTime?) - return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.fff"), "'"); - else if (param is TimeSpan || param is TimeSpan?) - return ((TimeSpan)param).Ticks / 10; - else if (param is MygisGeometry) - return string.Concat("ST_GeomFromText('", (param as MygisGeometry).AsText().Replace("'", "''"), "')"); - else if (param is IEnumerable) { - var sb = new StringBuilder(); - var ie = param as IEnumerable; - foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); - return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); - } - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - } + public MySqlAdo() : base(DataType.MySql) { } + public MySqlAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.MySql) + { + base._util = util; + if (!string.IsNullOrEmpty(masterConnectionString)) + MasterPool = new MySqlConnectionPool("主库", masterConnectionString, null, null); + if (slaveConnectionStrings != null) + { + foreach (var slaveConnectionString in slaveConnectionStrings) + { + var slavePool = new MySqlConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); + SlavePools.Add(slavePool); + } + } + } + static DateTime dt1970 = new DateTime(1970, 1, 1); + public override object AddslashesProcessParam(object param, Type mapType) + { + if (param == null) return "NULL"; + if (mapType != null && mapType != param.GetType()) + param = Utils.GetDataReaderValue(mapType, param); + if (param is bool || param is bool?) + return (bool)param ? 1 : 0; + else if (param is string || param is char) + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + else if (param is Enum) + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); //((Enum)val).ToInt64(); + else if (decimal.TryParse(string.Concat(param), out var trydec)) + return param; + else if (param is DateTime || param is DateTime?) + return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.fff"), "'"); + else if (param is TimeSpan || param is TimeSpan?) + return ((TimeSpan)param).Ticks / 10; + else if (param is MygisGeometry) + return string.Concat("ST_GeomFromText('", (param as MygisGeometry).AsText().Replace("'", "''"), "')"); + else if (param is IEnumerable) + { + var sb = new StringBuilder(); + var ie = param as IEnumerable; + foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); + return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); + } + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + } - protected override DbCommand CreateCommand() { - return new MySqlCommand(); - } + protected override DbCommand CreateCommand() + { + return new MySqlCommand(); + } - protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) { - (pool as MySqlConnectionPool).Return(conn, ex); - } + protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) + { + (pool as MySqlConnectionPool).Return(conn, ex); + } - protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); - } + protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); + } } diff --git a/Providers/FreeSql.Provider.MySql/MySqlAdo/MySqlConnectionPool.cs b/Providers/FreeSql.Provider.MySql/MySqlAdo/MySqlConnectionPool.cs index 548ff1aa..6d231602 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlAdo/MySqlConnectionPool.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlAdo/MySqlConnectionPool.cs @@ -8,170 +8,210 @@ using System.Data.Common; using System.Text.RegularExpressions; using System.Threading.Tasks; -namespace FreeSql.MySql { +namespace FreeSql.MySql +{ - class MySqlConnectionPool : ObjectPool { + class MySqlConnectionPool : ObjectPool + { - internal Action availableHandler; - internal Action unavailableHandler; + internal Action availableHandler; + internal Action unavailableHandler; - public MySqlConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) { - var policy = new MySqlConnectionPoolPolicy { - _pool = this, - Name = name - }; - this.Policy = policy; - policy.ConnectionString = connectionString; + public MySqlConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) + { + var policy = new MySqlConnectionPoolPolicy + { + _pool = this, + Name = name + }; + this.Policy = policy; + policy.ConnectionString = connectionString; - this.availableHandler = availableHandler; - this.unavailableHandler = unavailableHandler; - } + this.availableHandler = availableHandler; + this.unavailableHandler = unavailableHandler; + } - public void Return(Object obj, Exception exception, bool isRecreate = false) { - if (exception != null && exception is MySqlException) { - try { if (obj.Value.Ping() == false) obj.Value.Open(); } catch { base.SetUnavailable(exception); } - } - base.Return(obj, isRecreate); - } - } + public void Return(Object obj, Exception exception, bool isRecreate = false) + { + if (exception != null && exception is MySqlException) + { + try { if (obj.Value.Ping() == false) obj.Value.Open(); } catch { base.SetUnavailable(exception); } + } + base.Return(obj, isRecreate); + } + } - class MySqlConnectionPoolPolicy : IPolicy { + class MySqlConnectionPoolPolicy : IPolicy + { - internal MySqlConnectionPool _pool; - public string Name { get; set; } = "MySql MySqlConnection 对象池"; - public int PoolSize { get; set; } = 100; - public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); - public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; - public int AsyncGetCapacity { get; set; } = 10000; - public bool IsThrowGetTimeoutException { get; set; } = true; - public int CheckAvailableInterval { get; set; } = 5; + internal MySqlConnectionPool _pool; + public string Name { get; set; } = "MySql MySqlConnection 对象池"; + public int PoolSize { get; set; } = 100; + public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); + public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; + public int AsyncGetCapacity { get; set; } = 10000; + public bool IsThrowGetTimeoutException { get; set; } = true; + public int CheckAvailableInterval { get; set; } = 5; - static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - private string _connectionString; - public string ConnectionString { - get => _connectionString; - set { - _connectionString = value ?? ""; + static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + private string _connectionString; + public string ConnectionString + { + get => _connectionString; + set + { + _connectionString = value ?? ""; - var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)"; - var m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100; - var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); - PoolSize = poolsize + connStrIncr; - _connectionString = m.Success ? - Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) : - $"{_connectionString};Max pool size={PoolSize}"; + var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)"; + var m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100; + var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); + PoolSize = poolsize + connStrIncr; + _connectionString = m.Success ? + Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) : + $"{_connectionString};Max pool size={PoolSize}"; - pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - var minPoolSize = 0; - pattern = @"Min\s*pool\s*size\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - minPoolSize = int.Parse(m.Groups[1].Value); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + var minPoolSize = 0; + pattern = @"Min\s*pool\s*size\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + minPoolSize = int.Parse(m.Groups[1].Value); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); - } - } + FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); + } + } - public bool OnCheckAvailable(Object obj) { - if (obj.Value.State == ConnectionState.Closed) obj.Value.Open(); - return obj.Value.Ping(true); - } + public bool OnCheckAvailable(Object obj) + { + if (obj.Value.State == ConnectionState.Closed) obj.Value.Open(); + return obj.Value.Ping(true); + } - public DbConnection OnCreate() { - var conn = new MySqlConnection(_connectionString); - return conn; - } + public DbConnection OnCreate() + { + var conn = new MySqlConnection(_connectionString); + return conn; + } - public void OnDestroy(DbConnection obj) { - if (obj.State != ConnectionState.Closed) obj.Close(); - obj.Dispose(); - } + public void OnDestroy(DbConnection obj) + { + if (obj.State != ConnectionState.Closed) obj.Close(); + obj.Dispose(); + } - public void OnGet(Object obj) { + public void OnGet(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) + { - try { - obj.Value.Open(); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + obj.Value.Open(); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - async public Task OnGetAsync(Object obj) { + async public Task OnGetAsync(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) + { - try { - await obj.Value.OpenAsync(); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + await obj.Value.OpenAsync(); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - public void OnGetTimeout() { + public void OnGetTimeout() + { - } + } - public void OnReturn(Object obj) { + public void OnReturn(Object obj) + { - } + } - public void OnAvailable() { - _pool.availableHandler?.Invoke(); - } + public void OnAvailable() + { + _pool.availableHandler?.Invoke(); + } - public void OnUnavailable() { - _pool.unavailableHandler?.Invoke(); - } - } + public void OnUnavailable() + { + _pool.unavailableHandler?.Invoke(); + } + } - static class DbConnectionExtensions { + static class DbConnectionExtensions + { - static DbCommand PingCommand(DbConnection conn) { - var cmd = conn.CreateCommand(); - cmd.CommandTimeout = 5; - cmd.CommandText = "select 1"; - return cmd; - } - public static bool Ping(this DbConnection that, bool isThrow = false) { - try { - PingCommand(that).ExecuteNonQuery(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - async public static Task PingAsync(this DbConnection that, bool isThrow = false) { - try { - await PingCommand(that).ExecuteNonQueryAsync(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - } + static DbCommand PingCommand(DbConnection conn) + { + var cmd = conn.CreateCommand(); + cmd.CommandTimeout = 5; + cmd.CommandText = "select 1"; + return cmd; + } + public static bool Ping(this DbConnection that, bool isThrow = false) + { + try + { + PingCommand(that).ExecuteNonQuery(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + async public static Task PingAsync(this DbConnection that, bool isThrow = false) + { + try + { + await PingCommand(that).ExecuteNonQueryAsync(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + } } diff --git a/Providers/FreeSql.Provider.MySql/MySqlAdo/MygisTypes.cs b/Providers/FreeSql.Provider.MySql/MySqlAdo/MygisTypes.cs index e412141a..6672b628 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlAdo/MygisTypes.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlAdo/MygisTypes.cs @@ -4,289 +4,338 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -public struct MygisCoordinate2D : IEquatable { - public double X { get; } - public double Y { get; } - public MygisCoordinate2D(double x, double y) { X = x; Y = y; } +public struct MygisCoordinate2D : IEquatable +{ + public double X { get; } + public double Y { get; } + public MygisCoordinate2D(double x, double y) { X = x; Y = y; } - public bool Equals(MygisCoordinate2D c) => X == c.X && Y == c.Y; - public override int GetHashCode() => X.GetHashCode() ^ MygisGeometry.RotateShift(Y.GetHashCode(), sizeof(int) / 2); - public override bool Equals(object obj) => obj is MygisCoordinate2D && Equals((MygisCoordinate2D) obj); - public static bool operator ==(MygisCoordinate2D left, MygisCoordinate2D right) => Equals(left, right); - public static bool operator !=(MygisCoordinate2D left, MygisCoordinate2D right) => !Equals(left, right); + public bool Equals(MygisCoordinate2D c) => X == c.X && Y == c.Y; + public override int GetHashCode() => X.GetHashCode() ^ MygisGeometry.RotateShift(Y.GetHashCode(), sizeof(int) / 2); + public override bool Equals(object obj) => obj is MygisCoordinate2D && Equals((MygisCoordinate2D)obj); + public static bool operator ==(MygisCoordinate2D left, MygisCoordinate2D right) => Equals(left, right); + public static bool operator !=(MygisCoordinate2D left, MygisCoordinate2D right) => !Equals(left, right); } -public abstract class MygisGeometry { - protected abstract int GetLenHelper(); - internal int GetLen(bool includeSRID) => 5 + (SRID == 0 || !includeSRID ? 0 : 4) + GetLenHelper(); - public uint SRID { get; set; } = 0; - internal static int RotateShift(int val, int shift) => (val << shift) | (val >> (sizeof(int) - shift)); - public override string ToString() => this.AsText(); - public string AsText() { - if (this is MygisPoint) { - var obj = this as MygisPoint; - return $"POINT({obj.X} {obj.Y})"; - } - if (this is MygisLineString) { - var obj = this as MygisLineString; - return obj?.PointCount > 0 ? $"LINESTRING({string.Join(",", obj.Select(a => $"{a.X} {a.Y}"))})" : null; - } - if (this is MygisPolygon) { - var obj = (this as MygisPolygon).Where(z => z.Count() > 1 && z.First().Equals(z.Last())); - return obj.Any() ? $"POLYGON(({string.Join("),(", obj.Select(c => string.Join(",", c.Select(a => $"{a.X} {a.Y}"))))}))" : null; - } - if (this is MygisMultiPoint) { - var obj = this as MygisMultiPoint; - return obj?.PointCount > 0 ? $"MULTIPOINT({string.Join(",", obj.Select(a => $"{a.X} {a.Y}"))})" : null; - } - if (this is MygisMultiLineString) { - var obj = this as MygisMultiLineString; - return obj.LineCount > 0 ? $"MULTILINESTRING(({string.Join("),(", obj.Select(c => string.Join(",", c.Select(a => $"{a.X} {a.Y}"))))}))" : null; - } - if (this is MygisMultiPolygon) { - var obj = (this as MygisMultiPolygon)?.Where(z => z.Where(y => y.Count() > 1 && y.First().Equals(y.Last())).Any()); - return obj.Any() ? $"MULTIPOLYGON((({string.Join(")),((", obj.Select(d => string.Join("),(", d.Select(c => string.Join(",", c.Select(a => $"{a.X} {a.Y}"))))))})))" : null; - } - return base.ToString(); - } - static readonly Regex regexMygisPoint = new Regex(@"\s*(-?\d+\.?\d*)\s+(-?\d+\.?\d*)\s*"); - static readonly Regex regexSplit1 = new Regex(@"\)\s*,\s*\("); - static readonly Regex regexSplit2 = new Regex(@"\)\s*\)\s*,\s*\(\s*\("); - public static MygisGeometry Parse(string wkt) { - if (string.IsNullOrEmpty(wkt)) return null; - wkt = wkt.Trim(); - if (wkt.StartsWith("point", StringComparison.CurrentCultureIgnoreCase)) return ParsePoint(wkt.Substring(5).Trim('(', ')')); - else if (wkt.StartsWith("linestring", StringComparison.CurrentCultureIgnoreCase)) return new MygisLineString(ParseLineString(wkt.Substring(10).Trim('(', ')'))); - else if (wkt.StartsWith("polygon", StringComparison.CurrentCultureIgnoreCase)) return new MygisPolygon(ParsePolygon(wkt.Substring(7).Trim('(', ')'))); - else if (wkt.StartsWith("multipoint", StringComparison.CurrentCultureIgnoreCase)) return new MygisMultiPoint(ParseLineString(wkt.Substring(10).Trim('(', ')'))); - else if (wkt.StartsWith("multilinestring", StringComparison.CurrentCultureIgnoreCase)) return new MygisMultiLineString(ParseMultiLineString(wkt.Substring(15).Trim('(', ')'))); - else if (wkt.StartsWith("multipolygon", StringComparison.CurrentCultureIgnoreCase)) return new MygisMultiPolygon(ParseMultiPolygon(wkt.Substring(12).Trim('(', ')'))); - throw new NotImplementedException($"MygisGeometry.Parse 未实现 \"{wkt}\""); - } - static MygisPoint ParsePoint(string str) { - var m = regexMygisPoint.Match(str); - if (m.Success == false) return null; - return new MygisPoint(double.TryParse(m.Groups[1].Value, out var tryd) ? tryd : 0, double.TryParse(m.Groups[2].Value, out tryd) ? tryd : 0); - } - static MygisCoordinate2D[] ParseLineString(string str) { - var ms = regexMygisPoint.Matches(str); - var points = new MygisCoordinate2D[ms.Count]; - for (var a = 0; a < ms.Count; a++) points[a] = new MygisCoordinate2D(double.TryParse(ms[a].Groups[1].Value, out var tryd) ? tryd : 0, double.TryParse(ms[a].Groups[2].Value, out tryd) ? tryd : 0); - return points; - } - static MygisCoordinate2D[][] ParsePolygon(string str) { - return regexSplit1.Split(str).Select(s => ParseLineString(s)).Where(a => a.Length > 1 && a.First().Equals(a.Last())).ToArray(); - } - static MygisLineString[] ParseMultiLineString(string str) { - return regexSplit1.Split(str).Select(s => new MygisLineString(ParseLineString(s))).ToArray(); - } - static MygisPolygon[] ParseMultiPolygon(string str) { - return regexSplit2.Split(str).Select(s => new MygisPolygon(ParsePolygon(s))).ToArray(); - } +public abstract class MygisGeometry +{ + protected abstract int GetLenHelper(); + internal int GetLen(bool includeSRID) => 5 + (SRID == 0 || !includeSRID ? 0 : 4) + GetLenHelper(); + public uint SRID { get; set; } = 0; + internal static int RotateShift(int val, int shift) => (val << shift) | (val >> (sizeof(int) - shift)); + public override string ToString() => this.AsText(); + public string AsText() + { + if (this is MygisPoint) + { + var obj = this as MygisPoint; + return $"POINT({obj.X} {obj.Y})"; + } + if (this is MygisLineString) + { + var obj = this as MygisLineString; + return obj?.PointCount > 0 ? $"LINESTRING({string.Join(",", obj.Select(a => $"{a.X} {a.Y}"))})" : null; + } + if (this is MygisPolygon) + { + var obj = (this as MygisPolygon).Where(z => z.Count() > 1 && z.First().Equals(z.Last())); + return obj.Any() ? $"POLYGON(({string.Join("),(", obj.Select(c => string.Join(",", c.Select(a => $"{a.X} {a.Y}"))))}))" : null; + } + if (this is MygisMultiPoint) + { + var obj = this as MygisMultiPoint; + return obj?.PointCount > 0 ? $"MULTIPOINT({string.Join(",", obj.Select(a => $"{a.X} {a.Y}"))})" : null; + } + if (this is MygisMultiLineString) + { + var obj = this as MygisMultiLineString; + return obj.LineCount > 0 ? $"MULTILINESTRING(({string.Join("),(", obj.Select(c => string.Join(",", c.Select(a => $"{a.X} {a.Y}"))))}))" : null; + } + if (this is MygisMultiPolygon) + { + var obj = (this as MygisMultiPolygon)?.Where(z => z.Where(y => y.Count() > 1 && y.First().Equals(y.Last())).Any()); + return obj.Any() ? $"MULTIPOLYGON((({string.Join(")),((", obj.Select(d => string.Join("),(", d.Select(c => string.Join(",", c.Select(a => $"{a.X} {a.Y}"))))))})))" : null; + } + return base.ToString(); + } + static readonly Regex regexMygisPoint = new Regex(@"\s*(-?\d+\.?\d*)\s+(-?\d+\.?\d*)\s*"); + static readonly Regex regexSplit1 = new Regex(@"\)\s*,\s*\("); + static readonly Regex regexSplit2 = new Regex(@"\)\s*\)\s*,\s*\(\s*\("); + public static MygisGeometry Parse(string wkt) + { + if (string.IsNullOrEmpty(wkt)) return null; + wkt = wkt.Trim(); + if (wkt.StartsWith("point", StringComparison.CurrentCultureIgnoreCase)) return ParsePoint(wkt.Substring(5).Trim('(', ')')); + else if (wkt.StartsWith("linestring", StringComparison.CurrentCultureIgnoreCase)) return new MygisLineString(ParseLineString(wkt.Substring(10).Trim('(', ')'))); + else if (wkt.StartsWith("polygon", StringComparison.CurrentCultureIgnoreCase)) return new MygisPolygon(ParsePolygon(wkt.Substring(7).Trim('(', ')'))); + else if (wkt.StartsWith("multipoint", StringComparison.CurrentCultureIgnoreCase)) return new MygisMultiPoint(ParseLineString(wkt.Substring(10).Trim('(', ')'))); + else if (wkt.StartsWith("multilinestring", StringComparison.CurrentCultureIgnoreCase)) return new MygisMultiLineString(ParseMultiLineString(wkt.Substring(15).Trim('(', ')'))); + else if (wkt.StartsWith("multipolygon", StringComparison.CurrentCultureIgnoreCase)) return new MygisMultiPolygon(ParseMultiPolygon(wkt.Substring(12).Trim('(', ')'))); + throw new NotImplementedException($"MygisGeometry.Parse 未实现 \"{wkt}\""); + } + static MygisPoint ParsePoint(string str) + { + var m = regexMygisPoint.Match(str); + if (m.Success == false) return null; + return new MygisPoint(double.TryParse(m.Groups[1].Value, out var tryd) ? tryd : 0, double.TryParse(m.Groups[2].Value, out tryd) ? tryd : 0); + } + static MygisCoordinate2D[] ParseLineString(string str) + { + var ms = regexMygisPoint.Matches(str); + var points = new MygisCoordinate2D[ms.Count]; + for (var a = 0; a < ms.Count; a++) points[a] = new MygisCoordinate2D(double.TryParse(ms[a].Groups[1].Value, out var tryd) ? tryd : 0, double.TryParse(ms[a].Groups[2].Value, out tryd) ? tryd : 0); + return points; + } + static MygisCoordinate2D[][] ParsePolygon(string str) + { + return regexSplit1.Split(str).Select(s => ParseLineString(s)).Where(a => a.Length > 1 && a.First().Equals(a.Last())).ToArray(); + } + static MygisLineString[] ParseMultiLineString(string str) + { + return regexSplit1.Split(str).Select(s => new MygisLineString(ParseLineString(s))).ToArray(); + } + static MygisPolygon[] ParseMultiPolygon(string str) + { + return regexSplit2.Split(str).Select(s => new MygisPolygon(ParsePolygon(s))).ToArray(); + } } -public class MygisPoint : MygisGeometry, IEquatable { - MygisCoordinate2D _coord; - protected override int GetLenHelper() => 16; - public double X => _coord.X; - public double Y => _coord.Y; +public class MygisPoint : MygisGeometry, IEquatable +{ + MygisCoordinate2D _coord; + protected override int GetLenHelper() => 16; + public double X => _coord.X; + public double Y => _coord.Y; - public MygisPoint(double x, double y) { - _coord = new MygisCoordinate2D(x, y); - } + public MygisPoint(double x, double y) + { + _coord = new MygisCoordinate2D(x, y); + } - public bool Equals(MygisPoint other) => !ReferenceEquals(other, null) && _coord.Equals(other._coord); - public override bool Equals(object obj) => Equals(obj as MygisPoint); - public static bool operator ==(MygisPoint x, MygisPoint y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); - public static bool operator !=(MygisPoint x, MygisPoint y) => !(x == y); - public override int GetHashCode() => X.GetHashCode() ^ RotateShift(Y.GetHashCode(), sizeof(int) / 2); + public bool Equals(MygisPoint other) => !ReferenceEquals(other, null) && _coord.Equals(other._coord); + public override bool Equals(object obj) => Equals(obj as MygisPoint); + public static bool operator ==(MygisPoint x, MygisPoint y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); + public static bool operator !=(MygisPoint x, MygisPoint y) => !(x == y); + public override int GetHashCode() => X.GetHashCode() ^ RotateShift(Y.GetHashCode(), sizeof(int) / 2); } -public class MygisLineString : MygisGeometry, IEquatable, IEnumerable { - readonly MygisCoordinate2D[] _points; - protected override int GetLenHelper() => 4 + _points.Length * 16; - public IEnumerator GetEnumerator() => ((IEnumerable) _points).GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public MygisCoordinate2D this[int index] => _points[index]; - public int PointCount => _points.Length; +public class MygisLineString : MygisGeometry, IEquatable, IEnumerable +{ + readonly MygisCoordinate2D[] _points; + protected override int GetLenHelper() => 4 + _points.Length * 16; + public IEnumerator GetEnumerator() => ((IEnumerable)_points).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + public MygisCoordinate2D this[int index] => _points[index]; + public int PointCount => _points.Length; - public MygisLineString(IEnumerable points) { - _points = points.ToArray(); - } - public MygisLineString(MygisCoordinate2D[] points) { - _points = points; - } + public MygisLineString(IEnumerable points) + { + _points = points.ToArray(); + } + public MygisLineString(MygisCoordinate2D[] points) + { + _points = points; + } - public bool Equals(MygisLineString other) { - if (ReferenceEquals(other, null)) return false; - if (_points.Length != other._points.Length) return false; - for (var i = 0; i < _points.Length; i++) - if (!_points[i].Equals(other._points[i])) return false; - return true; - } - public override bool Equals(object obj) => Equals(obj as MygisLineString); - public static bool operator ==(MygisLineString x, MygisLineString y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); - public static bool operator !=(MygisLineString x, MygisLineString y) => !(x == y); - public override int GetHashCode() { - var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. - foreach (var t in _points) ret ^= RotateShift(t.GetHashCode(), ret % sizeof(int)); - return ret; - } + public bool Equals(MygisLineString other) + { + if (ReferenceEquals(other, null)) return false; + if (_points.Length != other._points.Length) return false; + for (var i = 0; i < _points.Length; i++) + if (!_points[i].Equals(other._points[i])) return false; + return true; + } + public override bool Equals(object obj) => Equals(obj as MygisLineString); + public static bool operator ==(MygisLineString x, MygisLineString y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); + public static bool operator !=(MygisLineString x, MygisLineString y) => !(x == y); + public override int GetHashCode() + { + var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. + foreach (var t in _points) ret ^= RotateShift(t.GetHashCode(), ret % sizeof(int)); + return ret; + } } -public class MygisPolygon : MygisGeometry, IEquatable, IEnumerable> { - readonly MygisCoordinate2D[][] _rings; - protected override int GetLenHelper() => 4 + _rings.Length * 4 + TotalPointCount * 16; - public MygisCoordinate2D this[int ringIndex, int pointIndex] => _rings[ringIndex][pointIndex]; - public MygisCoordinate2D[] this[int ringIndex] => _rings[ringIndex]; - public IEnumerator> GetEnumerator() => ((IEnumerable>) _rings).GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public int RingCount => _rings.Length; - public int TotalPointCount => _rings.Sum(r => r.Length); +public class MygisPolygon : MygisGeometry, IEquatable, IEnumerable> +{ + readonly MygisCoordinate2D[][] _rings; + protected override int GetLenHelper() => 4 + _rings.Length * 4 + TotalPointCount * 16; + public MygisCoordinate2D this[int ringIndex, int pointIndex] => _rings[ringIndex][pointIndex]; + public MygisCoordinate2D[] this[int ringIndex] => _rings[ringIndex]; + public IEnumerator> GetEnumerator() => ((IEnumerable>)_rings).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + public int RingCount => _rings.Length; + public int TotalPointCount => _rings.Sum(r => r.Length); - public MygisPolygon(MygisCoordinate2D[][] rings) { - _rings = rings; - } - public MygisPolygon(IEnumerable> rings) { - _rings = rings.Select(x => x.ToArray()).ToArray(); - } + public MygisPolygon(MygisCoordinate2D[][] rings) + { + _rings = rings; + } + public MygisPolygon(IEnumerable> rings) + { + _rings = rings.Select(x => x.ToArray()).ToArray(); + } - public bool Equals(MygisPolygon other) { - if (ReferenceEquals(other, null)) return false; - if (_rings.Length != other._rings.Length) return false; - for (var i = 0; i < _rings.Length; i++) { - if (_rings[i].Length != other._rings[i].Length) return false; - for (var j = 0; j < _rings[i].Length; j++) - if (!_rings[i][j].Equals(other._rings[i][j])) return false; - } - return true; - } - public override bool Equals(object obj) => Equals(obj as MygisPolygon); - public static bool operator ==(MygisPolygon x, MygisPolygon y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); - public static bool operator !=(MygisPolygon x, MygisPolygon y) => !(x == y); - public override int GetHashCode() { - var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. - for (var i = 0; i < _rings.Length; i++) - for (var j = 0; j < _rings[i].Length; j++) - ret ^= RotateShift(_rings[i][j].GetHashCode(), ret % sizeof(int)); - return ret; - } + public bool Equals(MygisPolygon other) + { + if (ReferenceEquals(other, null)) return false; + if (_rings.Length != other._rings.Length) return false; + for (var i = 0; i < _rings.Length; i++) + { + if (_rings[i].Length != other._rings[i].Length) return false; + for (var j = 0; j < _rings[i].Length; j++) + if (!_rings[i][j].Equals(other._rings[i][j])) return false; + } + return true; + } + public override bool Equals(object obj) => Equals(obj as MygisPolygon); + public static bool operator ==(MygisPolygon x, MygisPolygon y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); + public static bool operator !=(MygisPolygon x, MygisPolygon y) => !(x == y); + public override int GetHashCode() + { + var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. + for (var i = 0; i < _rings.Length; i++) + for (var j = 0; j < _rings[i].Length; j++) + ret ^= RotateShift(_rings[i][j].GetHashCode(), ret % sizeof(int)); + return ret; + } } -public class MygisMultiPoint : MygisGeometry, IEquatable, IEnumerable { - readonly MygisCoordinate2D[] _points; - protected override int GetLenHelper() => 4 + _points.Length * 21; - public IEnumerator GetEnumerator() => ((IEnumerable) _points).GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public MygisCoordinate2D this[int indexer] => _points[indexer]; - public int PointCount => _points.Length; +public class MygisMultiPoint : MygisGeometry, IEquatable, IEnumerable +{ + readonly MygisCoordinate2D[] _points; + protected override int GetLenHelper() => 4 + _points.Length * 21; + public IEnumerator GetEnumerator() => ((IEnumerable)_points).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + public MygisCoordinate2D this[int indexer] => _points[indexer]; + public int PointCount => _points.Length; - public MygisMultiPoint(MygisCoordinate2D[] points) { - _points = points; - } - public MygisMultiPoint(IEnumerable points) { - _points = points.Select(x => new MygisCoordinate2D(x.X, x.Y)).ToArray(); - } - public MygisMultiPoint(IEnumerable points) { - _points = points.ToArray(); - } + public MygisMultiPoint(MygisCoordinate2D[] points) + { + _points = points; + } + public MygisMultiPoint(IEnumerable points) + { + _points = points.Select(x => new MygisCoordinate2D(x.X, x.Y)).ToArray(); + } + public MygisMultiPoint(IEnumerable points) + { + _points = points.ToArray(); + } - public bool Equals(MygisMultiPoint other) { - if (ReferenceEquals(other, null)) return false; - if (_points.Length != other._points.Length) return false; - for (var i = 0; i < _points.Length; i++) - if (!_points[i].Equals(other._points[i])) return false; - return true; - } - public override bool Equals(object obj) => Equals(obj as MygisMultiPoint); - public static bool operator ==(MygisMultiPoint x, MygisMultiPoint y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); - public static bool operator !=(MygisMultiPoint x, MygisMultiPoint y) => !(x == y); - public override int GetHashCode() { - var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. - for (var i = 0; i < _points.Length; i++) ret ^= RotateShift(_points[i].GetHashCode(), ret % sizeof(int)); - return ret; - } + public bool Equals(MygisMultiPoint other) + { + if (ReferenceEquals(other, null)) return false; + if (_points.Length != other._points.Length) return false; + for (var i = 0; i < _points.Length; i++) + if (!_points[i].Equals(other._points[i])) return false; + return true; + } + public override bool Equals(object obj) => Equals(obj as MygisMultiPoint); + public static bool operator ==(MygisMultiPoint x, MygisMultiPoint y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); + public static bool operator !=(MygisMultiPoint x, MygisMultiPoint y) => !(x == y); + public override int GetHashCode() + { + var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. + for (var i = 0; i < _points.Length; i++) ret ^= RotateShift(_points[i].GetHashCode(), ret % sizeof(int)); + return ret; + } } public sealed class MygisMultiLineString : MygisGeometry, - IEquatable, IEnumerable { - readonly MygisLineString[] _lineStrings; - protected override int GetLenHelper() { - var n = 4; - for (var i = 0; i < _lineStrings.Length; i++) n += _lineStrings[i].GetLen(false); - return n; - } - public IEnumerator GetEnumerator() => ((IEnumerable) _lineStrings).GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public MygisLineString this[int index] => _lineStrings[index]; - public int LineCount => _lineStrings.Length; + IEquatable, IEnumerable +{ + readonly MygisLineString[] _lineStrings; + protected override int GetLenHelper() + { + var n = 4; + for (var i = 0; i < _lineStrings.Length; i++) n += _lineStrings[i].GetLen(false); + return n; + } + public IEnumerator GetEnumerator() => ((IEnumerable)_lineStrings).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + public MygisLineString this[int index] => _lineStrings[index]; + public int LineCount => _lineStrings.Length; - internal MygisMultiLineString(MygisCoordinate2D[][] pointArray) { - _lineStrings = new MygisLineString[pointArray.Length]; - for (var i = 0; i < pointArray.Length; i++) - _lineStrings[i] = new MygisLineString(pointArray[i]); - } - public MygisMultiLineString(MygisLineString[] linestrings) { - _lineStrings = linestrings; - } - public MygisMultiLineString(IEnumerable linestrings) { - _lineStrings = linestrings.ToArray(); - } - public MygisMultiLineString(IEnumerable> pointList) { - _lineStrings = pointList.Select(x => new MygisLineString(x)).ToArray(); - } + internal MygisMultiLineString(MygisCoordinate2D[][] pointArray) + { + _lineStrings = new MygisLineString[pointArray.Length]; + for (var i = 0; i < pointArray.Length; i++) + _lineStrings[i] = new MygisLineString(pointArray[i]); + } + public MygisMultiLineString(MygisLineString[] linestrings) + { + _lineStrings = linestrings; + } + public MygisMultiLineString(IEnumerable linestrings) + { + _lineStrings = linestrings.ToArray(); + } + public MygisMultiLineString(IEnumerable> pointList) + { + _lineStrings = pointList.Select(x => new MygisLineString(x)).ToArray(); + } - public bool Equals(MygisMultiLineString other) { - if (ReferenceEquals(other, null)) return false; - if (_lineStrings.Length != other._lineStrings.Length) return false; - for (var i = 0; i < _lineStrings.Length; i++) - if (_lineStrings[i] != other._lineStrings[i]) return false; - return true; - } - public override bool Equals(object obj) => Equals(obj as MygisMultiLineString); - public static bool operator ==(MygisMultiLineString x, MygisMultiLineString y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); - public static bool operator !=(MygisMultiLineString x, MygisMultiLineString y) => !(x == y); - public override int GetHashCode() { - var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. - for (var i = 0; i < _lineStrings.Length; i++) ret ^= RotateShift(_lineStrings[i].GetHashCode(), ret % sizeof(int)); - return ret; - } + public bool Equals(MygisMultiLineString other) + { + if (ReferenceEquals(other, null)) return false; + if (_lineStrings.Length != other._lineStrings.Length) return false; + for (var i = 0; i < _lineStrings.Length; i++) + if (_lineStrings[i] != other._lineStrings[i]) return false; + return true; + } + public override bool Equals(object obj) => Equals(obj as MygisMultiLineString); + public static bool operator ==(MygisMultiLineString x, MygisMultiLineString y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); + public static bool operator !=(MygisMultiLineString x, MygisMultiLineString y) => !(x == y); + public override int GetHashCode() + { + var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. + for (var i = 0; i < _lineStrings.Length; i++) ret ^= RotateShift(_lineStrings[i].GetHashCode(), ret % sizeof(int)); + return ret; + } } -public class MygisMultiPolygon : MygisGeometry, IEquatable, IEnumerable { - readonly MygisPolygon[] _polygons; - protected override int GetLenHelper() { - var n = 4; - for (var i = 0; i < _polygons.Length; i++) n += _polygons[i].GetLen(false); - return n; - } - public IEnumerator GetEnumerator() => ((IEnumerable) _polygons).GetEnumerator(); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public MygisPolygon this[int index] => _polygons[index]; - public int PolygonCount => _polygons.Length; +public class MygisMultiPolygon : MygisGeometry, IEquatable, IEnumerable +{ + readonly MygisPolygon[] _polygons; + protected override int GetLenHelper() + { + var n = 4; + for (var i = 0; i < _polygons.Length; i++) n += _polygons[i].GetLen(false); + return n; + } + public IEnumerator GetEnumerator() => ((IEnumerable)_polygons).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + public MygisPolygon this[int index] => _polygons[index]; + public int PolygonCount => _polygons.Length; - public MygisMultiPolygon(MygisPolygon[] polygons) { - _polygons = polygons; - } - public MygisMultiPolygon(IEnumerable polygons) { - _polygons = polygons.ToArray(); - } - public MygisMultiPolygon(IEnumerable>> ringList) { - _polygons = ringList.Select(x => new MygisPolygon(x)).ToArray(); - } + public MygisMultiPolygon(MygisPolygon[] polygons) + { + _polygons = polygons; + } + public MygisMultiPolygon(IEnumerable polygons) + { + _polygons = polygons.ToArray(); + } + public MygisMultiPolygon(IEnumerable>> ringList) + { + _polygons = ringList.Select(x => new MygisPolygon(x)).ToArray(); + } - public bool Equals(MygisMultiPolygon other) { - if (ReferenceEquals(other, null)) return false; - if (_polygons.Length != other._polygons.Length) return false; - for (var i = 0; i < _polygons.Length; i++) if (_polygons[i] != other._polygons[i]) return false; - return true; - } - public override bool Equals(object obj) => obj is MygisMultiPolygon && Equals((MygisMultiPolygon) obj); - public static bool operator ==(MygisMultiPolygon x, MygisMultiPolygon y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); - public static bool operator !=(MygisMultiPolygon x, MygisMultiPolygon y) => !(x == y); - public override int GetHashCode() { - var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. - for (var i = 0; i < _polygons.Length; i++) ret ^= RotateShift(_polygons[i].GetHashCode(), ret % sizeof(int)); - return ret; - } + public bool Equals(MygisMultiPolygon other) + { + if (ReferenceEquals(other, null)) return false; + if (_polygons.Length != other._polygons.Length) return false; + for (var i = 0; i < _polygons.Length; i++) if (_polygons[i] != other._polygons[i]) return false; + return true; + } + public override bool Equals(object obj) => obj is MygisMultiPolygon && Equals((MygisMultiPolygon)obj); + public static bool operator ==(MygisMultiPolygon x, MygisMultiPolygon y) => ReferenceEquals(x, null) ? ReferenceEquals(y, null) : x.Equals(y); + public static bool operator !=(MygisMultiPolygon x, MygisMultiPolygon y) => !(x == y); + public override int GetHashCode() + { + var ret = 266370105;//seed with something other than zero to make paths of all zeros hash differently. + for (var i = 0; i < _polygons.Length; i++) ret ^= RotateShift(_polygons[i].GetHashCode(), ret % sizeof(int)); + return ret; + } } diff --git a/Providers/FreeSql.Provider.MySql/MySqlAdo/MygisTypesExtensions.cs b/Providers/FreeSql.Provider.MySql/MySqlAdo/MygisTypesExtensions.cs index 5047e62e..ec45d367 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlAdo/MygisTypesExtensions.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlAdo/MygisTypesExtensions.cs @@ -6,18 +6,20 @@ using System.Drawing; using System.Reflection; using System.Text; -public static partial class MygisTypesExtensions { - /// - /// 测量两个经纬度的距离,返回单位:米 - /// - /// 经纬坐标1 - /// 经纬坐标2 - /// 返回距离(单位:米) - public static double Distance(this MygisPoint that, MygisPoint point) { - double radLat1 = (double)(that.Y) * Math.PI / 180d; - double radLng1 = (double)(that.X) * Math.PI / 180d; - double radLat2 = (double)(point.Y) * Math.PI / 180d; - double radLng2 = (double)(point.X) * Math.PI / 180d; - return 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((radLat1 - radLat2) / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin((radLng1 - radLng2) / 2), 2))) * 6378137; - } +public static partial class MygisTypesExtensions +{ + /// + /// 测量两个经纬度的距离,返回单位:米 + /// + /// 经纬坐标1 + /// 经纬坐标2 + /// 返回距离(单位:米) + public static double Distance(this MygisPoint that, MygisPoint point) + { + double radLat1 = (double)(that.Y) * Math.PI / 180d; + double radLng1 = (double)(that.X) * Math.PI / 180d; + double radLat2 = (double)(point.Y) * Math.PI / 180d; + double radLng2 = (double)(point.X) * Math.PI / 180d; + return 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((radLat1 - radLat2) / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin((radLng1 - radLng2) / 2), 2))) * 6378137; + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.MySql/MySqlCodeFirst.cs b/Providers/FreeSql.Provider.MySql/MySqlCodeFirst.cs index 8fed3c85..f4c5acc0 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlCodeFirst.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlCodeFirst.cs @@ -11,143 +11,165 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; -namespace FreeSql.MySql { +namespace FreeSql.MySql +{ - class MySqlCodeFirst : Internal.CommonProvider.CodeFirstProvider { + class MySqlCodeFirst : Internal.CommonProvider.CodeFirstProvider + { - public MySqlCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } + public MySqlCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } - static object _dicCsToDbLock = new object(); - static Dictionary _dicCsToDb = new Dictionary() { - { typeof(bool).FullName, (MySqlDbType.Bit, "bit","bit(1) NOT NULL", null, false, false) },{ typeof(bool?).FullName, (MySqlDbType.Bit, "bit","bit(1)", null, true, null) }, + static object _dicCsToDbLock = new object(); + static Dictionary _dicCsToDb = new Dictionary() { + { typeof(bool).FullName, (MySqlDbType.Bit, "bit","bit(1) NOT NULL", null, false, false) },{ typeof(bool?).FullName, (MySqlDbType.Bit, "bit","bit(1)", null, true, null) }, - { typeof(sbyte).FullName, (MySqlDbType.Byte, "tinyint", "tinyint(3) NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (MySqlDbType.Byte, "tinyint", "tinyint(3)", false, true, null) }, - { typeof(short).FullName, (MySqlDbType.Int16, "smallint","smallint(6) NOT NULL", false, false, 0) },{ typeof(short?).FullName, (MySqlDbType.Int16, "smallint", "smallint(6)", false, true, null) }, - { typeof(int).FullName, (MySqlDbType.Int32, "int", "int(11) NOT NULL", false, false, 0) },{ typeof(int?).FullName, (MySqlDbType.Int32, "int", "int(11)", false, true, null) }, - { typeof(long).FullName, (MySqlDbType.Int64, "bigint","bigint(20) NOT NULL", false, false, 0) },{ typeof(long?).FullName, (MySqlDbType.Int64, "bigint","bigint(20)", false, true, null) }, + { typeof(sbyte).FullName, (MySqlDbType.Byte, "tinyint", "tinyint(3) NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (MySqlDbType.Byte, "tinyint", "tinyint(3)", false, true, null) }, + { typeof(short).FullName, (MySqlDbType.Int16, "smallint","smallint(6) NOT NULL", false, false, 0) },{ typeof(short?).FullName, (MySqlDbType.Int16, "smallint", "smallint(6)", false, true, null) }, + { typeof(int).FullName, (MySqlDbType.Int32, "int", "int(11) NOT NULL", false, false, 0) },{ typeof(int?).FullName, (MySqlDbType.Int32, "int", "int(11)", false, true, null) }, + { typeof(long).FullName, (MySqlDbType.Int64, "bigint","bigint(20) NOT NULL", false, false, 0) },{ typeof(long?).FullName, (MySqlDbType.Int64, "bigint","bigint(20)", false, true, null) }, - { typeof(byte).FullName, (MySqlDbType.UByte, "tinyint","tinyint(3) unsigned NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (MySqlDbType.UByte, "tinyint","tinyint(3) unsigned", true, true, null) }, - { typeof(ushort).FullName, (MySqlDbType.UInt16, "smallint","smallint(5) unsigned NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (MySqlDbType.UInt16, "smallint", "smallint(5) unsigned", true, true, null) }, - { typeof(uint).FullName, (MySqlDbType.UInt32, "int", "int(10) unsigned NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (MySqlDbType.UInt32, "int", "int(10) unsigned", true, true, null) }, - { typeof(ulong).FullName, (MySqlDbType.UInt64, "bigint", "bigint(20) unsigned NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (MySqlDbType.UInt64, "bigint", "bigint(20) unsigned", true, true, null) }, + { typeof(byte).FullName, (MySqlDbType.UByte, "tinyint","tinyint(3) unsigned NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (MySqlDbType.UByte, "tinyint","tinyint(3) unsigned", true, true, null) }, + { typeof(ushort).FullName, (MySqlDbType.UInt16, "smallint","smallint(5) unsigned NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (MySqlDbType.UInt16, "smallint", "smallint(5) unsigned", true, true, null) }, + { typeof(uint).FullName, (MySqlDbType.UInt32, "int", "int(10) unsigned NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (MySqlDbType.UInt32, "int", "int(10) unsigned", true, true, null) }, + { typeof(ulong).FullName, (MySqlDbType.UInt64, "bigint", "bigint(20) unsigned NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (MySqlDbType.UInt64, "bigint", "bigint(20) unsigned", true, true, null) }, - { typeof(double).FullName, (MySqlDbType.Double, "double", "double NOT NULL", false, false, 0) },{ typeof(double?).FullName, (MySqlDbType.Double, "double", "double", false, true, null) }, - { typeof(float).FullName, (MySqlDbType.Float, "float","float NOT NULL", false, false, 0) },{ typeof(float?).FullName, (MySqlDbType.Float, "float","float", false, true, null) }, - { typeof(decimal).FullName, (MySqlDbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (MySqlDbType.Decimal, "decimal", "decimal(10,2)", false, true, null) }, + { typeof(double).FullName, (MySqlDbType.Double, "double", "double NOT NULL", false, false, 0) },{ typeof(double?).FullName, (MySqlDbType.Double, "double", "double", false, true, null) }, + { typeof(float).FullName, (MySqlDbType.Float, "float","float NOT NULL", false, false, 0) },{ typeof(float?).FullName, (MySqlDbType.Float, "float","float", false, true, null) }, + { typeof(decimal).FullName, (MySqlDbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (MySqlDbType.Decimal, "decimal", "decimal(10,2)", false, true, null) }, - { typeof(TimeSpan).FullName, (MySqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (MySqlDbType.Time, "time", "time",false, true, null) }, - { typeof(DateTime).FullName, (MySqlDbType.DateTime, "datetime(3)", "datetime(3) NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (MySqlDbType.DateTime, "datetime(3)", "datetime(3)", false, true, null) }, + { typeof(TimeSpan).FullName, (MySqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (MySqlDbType.Time, "time", "time",false, true, null) }, + { typeof(DateTime).FullName, (MySqlDbType.DateTime, "datetime(3)", "datetime(3) NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (MySqlDbType.DateTime, "datetime(3)", "datetime(3)", false, true, null) }, - { typeof(byte[]).FullName, (MySqlDbType.VarBinary, "varbinary", "varbinary(255)", false, null, new byte[0]) }, - { typeof(string).FullName, (MySqlDbType.VarChar, "varchar", "varchar(255)", false, null, "") }, + { typeof(byte[]).FullName, (MySqlDbType.VarBinary, "varbinary", "varbinary(255)", false, null, new byte[0]) }, + { typeof(string).FullName, (MySqlDbType.VarChar, "varchar", "varchar(255)", false, null, "") }, - { typeof(Guid).FullName, (MySqlDbType.VarChar, "char", "char(36) NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (MySqlDbType.VarChar, "char", "char(36)", false, true, null) }, + { typeof(Guid).FullName, (MySqlDbType.VarChar, "char", "char(36) NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (MySqlDbType.VarChar, "char", "char(36)", false, true, null) }, - { typeof(MygisPoint).FullName, (MySqlDbType.Geometry, "point", "point", false, null, new MygisPoint(0, 0)) }, - { typeof(MygisLineString).FullName, (MySqlDbType.Geometry, "linestring", "linestring", false, null, new MygisLineString(new[]{new MygisCoordinate2D(),new MygisCoordinate2D()})) }, - { typeof(MygisPolygon).FullName, (MySqlDbType.Geometry, "polygon", "polygon", false, null, new MygisPolygon(new[]{new[]{new MygisCoordinate2D(),new MygisCoordinate2D()},new[]{new MygisCoordinate2D(),new MygisCoordinate2D()}})) }, - { typeof(MygisMultiPoint).FullName, (MySqlDbType.Geometry, "multipoint","multipoint", false, null, new MygisMultiPoint(new[]{new MygisCoordinate2D(),new MygisCoordinate2D()})) }, - { typeof(MygisMultiLineString).FullName, (MySqlDbType.Geometry, "multilinestring","multilinestring", false, null, new MygisMultiLineString(new[]{new[]{new MygisCoordinate2D(),new MygisCoordinate2D()},new[]{new MygisCoordinate2D(),new MygisCoordinate2D()}})) }, - { typeof(MygisMultiPolygon).FullName, (MySqlDbType.Geometry, "multipolygon", "multipolygon", false, null, new MygisMultiPolygon(new[]{new MygisPolygon(new[]{new[]{new MygisCoordinate2D(),new MygisCoordinate2D()},new[]{new MygisCoordinate2D(),new MygisCoordinate2D()}}),new MygisPolygon(new[]{new[]{new MygisCoordinate2D(),new MygisCoordinate2D()},new[]{new MygisCoordinate2D(),new MygisCoordinate2D()}})})) }, - }; + { typeof(MygisPoint).FullName, (MySqlDbType.Geometry, "point", "point", false, null, new MygisPoint(0, 0)) }, + { typeof(MygisLineString).FullName, (MySqlDbType.Geometry, "linestring", "linestring", false, null, new MygisLineString(new[]{new MygisCoordinate2D(),new MygisCoordinate2D()})) }, + { typeof(MygisPolygon).FullName, (MySqlDbType.Geometry, "polygon", "polygon", false, null, new MygisPolygon(new[]{new[]{new MygisCoordinate2D(),new MygisCoordinate2D()},new[]{new MygisCoordinate2D(),new MygisCoordinate2D()}})) }, + { typeof(MygisMultiPoint).FullName, (MySqlDbType.Geometry, "multipoint","multipoint", false, null, new MygisMultiPoint(new[]{new MygisCoordinate2D(),new MygisCoordinate2D()})) }, + { typeof(MygisMultiLineString).FullName, (MySqlDbType.Geometry, "multilinestring","multilinestring", false, null, new MygisMultiLineString(new[]{new[]{new MygisCoordinate2D(),new MygisCoordinate2D()},new[]{new MygisCoordinate2D(),new MygisCoordinate2D()}})) }, + { typeof(MygisMultiPolygon).FullName, (MySqlDbType.Geometry, "multipolygon", "multipolygon", false, null, new MygisMultiPolygon(new[]{new MygisPolygon(new[]{new[]{new MygisCoordinate2D(),new MygisCoordinate2D()},new[]{new MygisCoordinate2D(),new MygisCoordinate2D()}}),new MygisPolygon(new[]{new[]{new MygisCoordinate2D(),new MygisCoordinate2D()},new[]{new MygisCoordinate2D(),new MygisCoordinate2D()}})})) }, + }; - public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) { - if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); - if (type.IsArray) return null; - var enumType = type.IsEnum ? type : null; - if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); - if (enumType != null) { - var names = string.Join(",", Enum.GetNames(enumType).Select(a => _commonUtils.FormatSql("{0}", a))); - var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? - (MySqlDbType.Set, "set", $"set({names}){(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : - (MySqlDbType.Enum, "enum", $"enum({names}){(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); - if (_dicCsToDb.ContainsKey(type.FullName) == false) { - lock (_dicCsToDbLock) { - if (_dicCsToDb.ContainsKey(type.FullName) == false) - _dicCsToDb.Add(type.FullName, newItem); - } - } - return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); - } - return null; - } + public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) + { + if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); + if (type.IsArray) return null; + var enumType = type.IsEnum ? type : null; + if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); + if (enumType != null) + { + var names = string.Join(",", Enum.GetNames(enumType).Select(a => _commonUtils.FormatSql("{0}", a))); + var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? + (MySqlDbType.Set, "set", $"set({names}){(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : + (MySqlDbType.Enum, "enum", $"enum({names}){(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); + if (_dicCsToDb.ContainsKey(type.FullName) == false) + { + lock (_dicCsToDbLock) + { + if (_dicCsToDb.ContainsKey(type.FullName) == false) + _dicCsToDb.Add(type.FullName, newItem); + } + } + return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); + } + return null; + } - public override string GetComparisonDDLStatements(params Type[] entityTypes) { - var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5)); - var database = conn.Value.Database; - Func ExecuteScalar = (db, sql) => { - if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(db); - try { - using (var cmd = conn.Value.CreateCommand()) { - cmd.CommandText = sql; - cmd.CommandType = CommandType.Text; - return cmd.ExecuteScalar(); - } - } finally { - if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(database); - } - }; - var sb = new StringBuilder(); - try { - foreach (var entityType in entityTypes) { - if (sb.Length > 0) sb.Append("\r\n"); - var tb = _commonUtils.GetTableByEntity(entityType); - if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); - if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); - var tbname = tb.DbName.Split(new[] { '.' }, 2); - if (tbname?.Length == 1) tbname = new[] { database, tbname[0] }; + public override string GetComparisonDDLStatements(params Type[] entityTypes) + { + var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5)); + var database = conn.Value.Database; + Func ExecuteScalar = (db, sql) => + { + if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(db); + try + { + using (var cmd = conn.Value.CreateCommand()) + { + cmd.CommandText = sql; + cmd.CommandType = CommandType.Text; + return cmd.ExecuteScalar(); + } + } + finally + { + if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(database); + } + }; + var sb = new StringBuilder(); + try + { + foreach (var entityType in entityTypes) + { + if (sb.Length > 0) sb.Append("\r\n"); + var tb = _commonUtils.GetTableByEntity(entityType); + if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); + if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); + var tbname = tb.DbName.Split(new[] { '.' }, 2); + if (tbname?.Length == 1) tbname = new[] { database, tbname[0] }; - var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名 - if (tboldname?.Length == 1) tboldname = new[] { database, tboldname[0] }; + var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名 + if (tboldname?.Length == 1) tboldname = new[] { database, tboldname[0] }; - if (string.Compare(tbname[0], database, true) != 0 && ExecuteScalar(database, _commonUtils.FormatSql(" select 1 from information_schema.schemata where schema_name={0}", tbname[0])) == null) //创建数据库 - sb.Append($"CREATE DATABASE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(" default charset utf8 COLLATE utf8_general_ci;\r\n"); + if (string.Compare(tbname[0], database, true) != 0 && ExecuteScalar(database, _commonUtils.FormatSql(" select 1 from information_schema.schemata where schema_name={0}", tbname[0])) == null) //创建数据库 + sb.Append($"CREATE DATABASE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(" default charset utf8 COLLATE utf8_general_ci;\r\n"); - var sbalter = new StringBuilder(); - var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 - if (ExecuteScalar(tbname[0], _commonUtils.FormatSql(" SELECT 1 FROM information_schema.TABLES WHERE table_schema={0} and table_name={1}", tbname)) == null) { //表不存在 - if (tboldname != null) { - if (string.Compare(tboldname[0], tbname[0], true) != 0 && ExecuteScalar(database, _commonUtils.FormatSql(" select 1 from information_schema.schemata where schema_name={0}", tboldname[0])) == null || - ExecuteScalar(tboldname[0], _commonUtils.FormatSql(" SELECT 1 FROM information_schema.TABLES WHERE table_schema={0} and table_name={1}", tboldname)) == null) - //数据库或表不存在 - tboldname = null; - } - if (tboldname == null) { - //创建表 - sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( "); - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" AUTO_INCREMENT"); - if (string.IsNullOrEmpty(tbcol.Comment) == false) sb.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)); - sb.Append(","); - } - if (tb.Primarys.Any()) { - sb.Append(" \r\n PRIMARY KEY ("); - foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n UNIQUE KEY ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1); - sb.Append("\r\n) Engine=InnoDB;\r\n"); - continue; - } - //如果新表,旧表在一个数据库下,直接修改表名 - if (string.Compare(tbname[0], tboldname[0], true) == 0) - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}")).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(";\r\n"); - else { - //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 - istmpatler = true; - } - } else - tboldname = null; //如果新表已经存在,不走改表名逻辑 + var sbalter = new StringBuilder(); + var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 + if (ExecuteScalar(tbname[0], _commonUtils.FormatSql(" SELECT 1 FROM information_schema.TABLES WHERE table_schema={0} and table_name={1}", tbname)) == null) + { //表不存在 + if (tboldname != null) + { + if (string.Compare(tboldname[0], tbname[0], true) != 0 && ExecuteScalar(database, _commonUtils.FormatSql(" select 1 from information_schema.schemata where schema_name={0}", tboldname[0])) == null || + ExecuteScalar(tboldname[0], _commonUtils.FormatSql(" SELECT 1 FROM information_schema.TABLES WHERE table_schema={0} and table_name={1}", tboldname)) == null) + //数据库或表不存在 + tboldname = null; + } + if (tboldname == null) + { + //创建表 + sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( "); + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); + sb.Append(tbcol.Attribute.DbType); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" AUTO_INCREMENT"); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sb.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)); + sb.Append(","); + } + if (tb.Primarys.Any()) + { + sb.Append(" \r\n PRIMARY KEY ("); + foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n UNIQUE KEY ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1); + sb.Append("\r\n) Engine=InnoDB;\r\n"); + continue; + } + //如果新表,旧表在一个数据库下,直接修改表名 + if (string.Compare(tbname[0], tboldname[0], true) == 0) + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}")).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(";\r\n"); + else + { + //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 + istmpatler = true; + } + } + else + tboldname = null; //如果新表已经存在,不走改表名逻辑 - //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 - var sql = _commonUtils.FormatSql(@" + //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 + var sql = _commonUtils.FormatSql(@" select a.column_name, a.column_type, @@ -156,131 +178,153 @@ case when locate('auto_increment', a.extra) > 0 then 1 else 0 end 'is_identity', a.column_comment 'comment' from information_schema.columns a where a.table_schema in ({0}) and a.table_name in ({1})", tboldname ?? tbname); - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => { - var a1 = string.Concat(a[1]); - if (a1 == "datetime") a1 = string.Concat(a1, "(0)"); - return new { - column = string.Concat(a[0]), - sqlType = a1, - is_nullable = string.Concat(a[2]) == "1", - is_identity = string.Concat(a[3]) == "1", - is_unsigned = string.Concat(a[1]).EndsWith(" unsigned"), - comment = string.Concat(a[4]) - }; - }, StringComparer.CurrentCultureIgnoreCase); + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => + { + var a1 = string.Concat(a[1]); + if (a1 == "datetime") a1 = string.Concat(a1, "(0)"); + return new + { + column = string.Concat(a[0]), + sqlType = a1, + is_nullable = string.Concat(a[2]) == "1", + is_identity = string.Concat(a[3]) == "1", + is_unsigned = string.Concat(a[1]).EndsWith(" unsigned"), + comment = string.Concat(a[4]) + }; + }, StringComparer.CurrentCultureIgnoreCase); - if (istmpatler == false) { - var existsPrimary = ExecuteScalar(tbname[0], _commonUtils.FormatSql("select 1 from information_schema.key_column_usage where table_schema={0} and table_name={1} and constraint_name = 'PRIMARY' limit 1", tbname)); - foreach (var tbcol in tb.Columns.Values) { - var isIdentityChanged = tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1; - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? ""); - if ((tbcol.Attribute.DbType.IndexOf(" unsigned", StringComparison.CurrentCultureIgnoreCase) != -1) != tbstructcol.is_unsigned || - tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false || - tbcol.Attribute.IsNullable != tbstructcol.is_nullable || - tbcol.Attribute.IsIdentity != tbstructcol.is_identity || - isCommentChanged) { - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.DbType); - if (isCommentChanged) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(")"); - sbalter.Append(";\r\n"); - } - if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) { - //修改列名 - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" CHANGE COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); - if (isCommentChanged) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); - sbalter.Append(";\r\n"); - } - continue; - } - //添加列 - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsNullable == false) sbalter.Append(" DEFAULT ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)); - if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); - if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); - sbalter.Append(";\r\n"); - } - var dsuksql = _commonUtils.FormatSql(@" + if (istmpatler == false) + { + var existsPrimary = ExecuteScalar(tbname[0], _commonUtils.FormatSql("select 1 from information_schema.key_column_usage where table_schema={0} and table_name={1} and constraint_name = 'PRIMARY' limit 1", tbname)); + foreach (var tbcol in tb.Columns.Values) + { + var isIdentityChanged = tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1; + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? ""); + if ((tbcol.Attribute.DbType.IndexOf(" unsigned", StringComparison.CurrentCultureIgnoreCase) != -1) != tbstructcol.is_unsigned || + tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false || + tbcol.Attribute.IsNullable != tbstructcol.is_nullable || + tbcol.Attribute.IsIdentity != tbstructcol.is_identity || + isCommentChanged) + { + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.DbType); + if (isCommentChanged) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); + if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(")"); + sbalter.Append(";\r\n"); + } + if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) + { + //修改列名 + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" CHANGE COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); + if (isCommentChanged) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); + if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); + sbalter.Append(";\r\n"); + } + continue; + } + //添加列 + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); + if (tbcol.Attribute.IsNullable == false) sbalter.Append(" DEFAULT ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")); + if (isIdentityChanged) sbalter.Append(" AUTO_INCREMENT").Append(existsPrimary == null ? "" : ", DROP PRIMARY KEY").Append(", ADD PRIMARY KEY(").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(")"); + sbalter.Append(";\r\n"); + } + var dsuksql = _commonUtils.FormatSql(@" select a.column_name, a.constraint_name 'index_id' from information_schema.key_column_usage a where a.constraint_schema IN ({0}) and a.table_name IN ({1})", tboldname ?? tbname); - var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) }); - foreach (var uk in tb.Uniques) { - if (uk.Key == "PRIMARY" || string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; - var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); - if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) { - if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n"); - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n"); - } - } - } - if (istmpatler == false) { - sb.Append(sbalter); - continue; - } + var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) }); + foreach (var uk in tb.Uniques) + { + if (uk.Key == "PRIMARY" || string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; + var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); + if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) + { + if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n"); + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n"); + } + } + } + if (istmpatler == false) + { + sb.Append(sbalter); + continue; + } - //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 - var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"); - var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.FreeSqlTmp_{tbname[1]}"); - //创建临时表 - sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" AUTO_INCREMENT"); - if (string.IsNullOrEmpty(tbcol.Comment) == false) sb.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)); - sb.Append(","); - } - if (tb.Primarys.Any()) { - sb.Append(" \r\n PRIMARY KEY ("); - foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n UNIQUE KEY ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1); - sb.Append("\r\n) Engine=InnoDB;\r\n"); - sb.Append("INSERT INTO ").Append(tmptablename).Append(" ("); - foreach (var tbcol in tb.Columns.Values) - sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append(")\r\nSELECT "); - foreach (var tbcol in tb.Columns.Values) { - var insertvalue = "NULL"; - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) { - //insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; - } - if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"ifnull({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; - } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); - sb.Append(insertvalue).Append(", "); - } - sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); - sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n"); - sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(";\r\n"); - } - return sb.Length == 0 ? null : sb.ToString(); - } finally { - try { - conn.Value.ChangeDatabase(database); - _orm.Ado.MasterPool.Return(conn); - } catch { - _orm.Ado.MasterPool.Return(conn, true); - } - } - } - } + //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 + var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"); + var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.FreeSqlTmp_{tbname[1]}"); + //创建临时表 + sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); + sb.Append(tbcol.Attribute.DbType); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTO_INCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" AUTO_INCREMENT"); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sb.Append(" COMMENT ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)); + sb.Append(","); + } + if (tb.Primarys.Any()) + { + sb.Append(" \r\n PRIMARY KEY ("); + foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n UNIQUE KEY ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1); + sb.Append("\r\n) Engine=InnoDB;\r\n"); + sb.Append("INSERT INTO ").Append(tmptablename).Append(" ("); + foreach (var tbcol in tb.Columns.Values) + sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append(")\r\nSELECT "); + foreach (var tbcol in tb.Columns.Values) + { + var insertvalue = "NULL"; + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) + { + //insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; + } + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) + insertvalue = $"ifnull({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + } + else if (tbcol.Attribute.IsNullable == false) + insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + sb.Append(insertvalue).Append(", "); + } + sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); + sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n"); + sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(";\r\n"); + } + return sb.Length == 0 ? null : sb.ToString(); + } + finally + { + try + { + conn.Value.ChangeDatabase(database); + _orm.Ado.MasterPool.Return(conn); + } + catch + { + _orm.Ado.MasterPool.Return(conn, true); + } + } + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.MySql/MySqlDbFirst.cs b/Providers/FreeSql.Provider.MySql/MySqlDbFirst.cs index 760aedc3..2f2a339a 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlDbFirst.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlDbFirst.cs @@ -7,149 +7,158 @@ using System.Data; using System.Linq; using System.Text.RegularExpressions; -namespace FreeSql.MySql { - class MySqlDbFirst : IDbFirst { - IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - public MySqlDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - } +namespace FreeSql.MySql +{ + class MySqlDbFirst : IDbFirst + { + IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + public MySqlDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + } - public int GetDbType(DbColumnInfo column) => (int)GetMySqlDbType(column); - MySqlDbType GetMySqlDbType(DbColumnInfo column) { - var is_unsigned = column.DbTypeTextFull.ToLower().EndsWith(" unsigned"); - switch (column.DbTypeText.ToLower()) { - case "bit": return MySqlDbType.Bit; + public int GetDbType(DbColumnInfo column) => (int)GetMySqlDbType(column); + MySqlDbType GetMySqlDbType(DbColumnInfo column) + { + var is_unsigned = column.DbTypeTextFull.ToLower().EndsWith(" unsigned"); + switch (column.DbTypeText.ToLower()) + { + case "bit": return MySqlDbType.Bit; - case "tinyint": return is_unsigned ? MySqlDbType.UByte : MySqlDbType.Byte; - case "smallint": return is_unsigned ? MySqlDbType.UInt16 : MySqlDbType.Int16; - case "mediumint": return is_unsigned ? MySqlDbType.UInt24 : MySqlDbType.Int24; - case "int": return is_unsigned ? MySqlDbType.UInt32 : MySqlDbType.Int32; - case "bigint": return is_unsigned ? MySqlDbType.UInt64 : MySqlDbType.Int64; + case "tinyint": return is_unsigned ? MySqlDbType.UByte : MySqlDbType.Byte; + case "smallint": return is_unsigned ? MySqlDbType.UInt16 : MySqlDbType.Int16; + case "mediumint": return is_unsigned ? MySqlDbType.UInt24 : MySqlDbType.Int24; + case "int": return is_unsigned ? MySqlDbType.UInt32 : MySqlDbType.Int32; + case "bigint": return is_unsigned ? MySqlDbType.UInt64 : MySqlDbType.Int64; - case "real": - case "double": return MySqlDbType.Double; - case "float": return MySqlDbType.Float; - case "numeric": - case "decimal": return MySqlDbType.Decimal; + case "real": + case "double": return MySqlDbType.Double; + case "float": return MySqlDbType.Float; + case "numeric": + case "decimal": return MySqlDbType.Decimal; - case "year": return MySqlDbType.Year; - case "time": return MySqlDbType.Time; - case "date": return MySqlDbType.Date; - case "timestamp": return MySqlDbType.Timestamp; - case "datetime": return MySqlDbType.DateTime; + case "year": return MySqlDbType.Year; + case "time": return MySqlDbType.Time; + case "date": return MySqlDbType.Date; + case "timestamp": return MySqlDbType.Timestamp; + case "datetime": return MySqlDbType.DateTime; - case "tinyblob": return MySqlDbType.TinyBlob; - case "blob": return MySqlDbType.Blob; - case "mediumblob": return MySqlDbType.MediumBlob; - case "longblob": return MySqlDbType.LongBlob; + case "tinyblob": return MySqlDbType.TinyBlob; + case "blob": return MySqlDbType.Blob; + case "mediumblob": return MySqlDbType.MediumBlob; + case "longblob": return MySqlDbType.LongBlob; - case "binary": return MySqlDbType.Binary; - case "varbinary": return MySqlDbType.VarBinary; + case "binary": return MySqlDbType.Binary; + case "varbinary": return MySqlDbType.VarBinary; - case "tinytext": return MySqlDbType.TinyText; - case "text": return MySqlDbType.Text; - case "mediumtext": return MySqlDbType.MediumText; - case "longtext": return MySqlDbType.LongText; + case "tinytext": return MySqlDbType.TinyText; + case "text": return MySqlDbType.Text; + case "mediumtext": return MySqlDbType.MediumText; + case "longtext": return MySqlDbType.LongText; - case "char": return column.MaxLength == 36 ? MySqlDbType.Guid : MySqlDbType.String; - case "varchar": return MySqlDbType.VarChar; + case "char": return column.MaxLength == 36 ? MySqlDbType.Guid : MySqlDbType.String; + case "varchar": return MySqlDbType.VarChar; - case "set": return MySqlDbType.Set; - case "enum": return MySqlDbType.Enum; + case "set": return MySqlDbType.Set; + case "enum": return MySqlDbType.Enum; - case "point": return MySqlDbType.Geometry; - case "linestring": return MySqlDbType.Geometry; - case "polygon": return MySqlDbType.Geometry; - case "geometry": return MySqlDbType.Geometry; - case "multipoint": return MySqlDbType.Geometry; - case "multilinestring": return MySqlDbType.Geometry; - case "multipolygon": return MySqlDbType.Geometry; - case "geometrycollection": return MySqlDbType.Geometry; - default: return MySqlDbType.String; - } - } + case "point": return MySqlDbType.Geometry; + case "linestring": return MySqlDbType.Geometry; + case "polygon": return MySqlDbType.Geometry; + case "geometry": return MySqlDbType.Geometry; + case "multipoint": return MySqlDbType.Geometry; + case "multilinestring": return MySqlDbType.Geometry; + case "multipolygon": return MySqlDbType.Geometry; + case "geometrycollection": return MySqlDbType.Geometry; + default: return MySqlDbType.String; + } + } - static readonly Dictionary _dicDbToCs = new Dictionary() { - { (int)MySqlDbType.Bit, ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, + static readonly Dictionary _dicDbToCs = new Dictionary() { + { (int)MySqlDbType.Bit, ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, - { (int)MySqlDbType.Byte, ("(sbyte?)", "sbyte.Parse({0})", "{0}.ToString()", "sbyte?", typeof(sbyte), typeof(sbyte?), "{0}.Value", "GetByte") }, - { (int)MySqlDbType.Int16, ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, - { (int)MySqlDbType.Int24, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, - { (int)MySqlDbType.Int32, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, - { (int)MySqlDbType.Int64, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, + { (int)MySqlDbType.Byte, ("(sbyte?)", "sbyte.Parse({0})", "{0}.ToString()", "sbyte?", typeof(sbyte), typeof(sbyte?), "{0}.Value", "GetByte") }, + { (int)MySqlDbType.Int16, ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, + { (int)MySqlDbType.Int24, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, + { (int)MySqlDbType.Int32, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, + { (int)MySqlDbType.Int64, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, - { (int)MySqlDbType.UByte, ("(byte?)", "byte.Parse({0})", "{0}.ToString()", "byte?", typeof(byte), typeof(byte?), "{0}.Value", "GetByte") }, - { (int)MySqlDbType.UInt16, ("(ushort?)", "ushort.Parse({0})", "{0}.ToString()", "ushort?", typeof(ushort), typeof(ushort?), "{0}.Value", "GetInt16") }, - { (int)MySqlDbType.UInt24, ("(uint?)", "uint.Parse({0})", "{0}.ToString()", "uint?", typeof(uint), typeof(uint?), "{0}.Value", "GetInt32") }, - { (int)MySqlDbType.UInt32, ("(uint?)", "uint.Parse({0})", "{0}.ToString()", "uint?", typeof(uint), typeof(uint?), "{0}.Value", "GetInt32") }, - { (int)MySqlDbType.UInt64, ("(ulong?)", "ulong.Parse({0})", "{0}.ToString()", "ulong?", typeof(ulong), typeof(ulong?), "{0}.Value", "GetInt64") }, + { (int)MySqlDbType.UByte, ("(byte?)", "byte.Parse({0})", "{0}.ToString()", "byte?", typeof(byte), typeof(byte?), "{0}.Value", "GetByte") }, + { (int)MySqlDbType.UInt16, ("(ushort?)", "ushort.Parse({0})", "{0}.ToString()", "ushort?", typeof(ushort), typeof(ushort?), "{0}.Value", "GetInt16") }, + { (int)MySqlDbType.UInt24, ("(uint?)", "uint.Parse({0})", "{0}.ToString()", "uint?", typeof(uint), typeof(uint?), "{0}.Value", "GetInt32") }, + { (int)MySqlDbType.UInt32, ("(uint?)", "uint.Parse({0})", "{0}.ToString()", "uint?", typeof(uint), typeof(uint?), "{0}.Value", "GetInt32") }, + { (int)MySqlDbType.UInt64, ("(ulong?)", "ulong.Parse({0})", "{0}.ToString()", "ulong?", typeof(ulong), typeof(ulong?), "{0}.Value", "GetInt64") }, - { (int)MySqlDbType.Double, ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, - { (int)MySqlDbType.Float, ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, - { (int)MySqlDbType.Decimal, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, + { (int)MySqlDbType.Double, ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, + { (int)MySqlDbType.Float, ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, + { (int)MySqlDbType.Decimal, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, - { (int)MySqlDbType.Year, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, - { (int)MySqlDbType.Time, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, - { (int)MySqlDbType.Date, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)MySqlDbType.Timestamp, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)MySqlDbType.DateTime, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)MySqlDbType.Year, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, + { (int)MySqlDbType.Time, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, + { (int)MySqlDbType.Date, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)MySqlDbType.Timestamp, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)MySqlDbType.DateTime, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)MySqlDbType.TinyBlob, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)MySqlDbType.Blob, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)MySqlDbType.MediumBlob, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)MySqlDbType.LongBlob, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)MySqlDbType.TinyBlob, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)MySqlDbType.Blob, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)MySqlDbType.MediumBlob, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)MySqlDbType.LongBlob, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)MySqlDbType.Binary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)MySqlDbType.VarBinary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)MySqlDbType.Binary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)MySqlDbType.VarBinary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)MySqlDbType.TinyText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)MySqlDbType.Text, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)MySqlDbType.MediumText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)MySqlDbType.LongText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)MySqlDbType.TinyText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)MySqlDbType.Text, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)MySqlDbType.MediumText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)MySqlDbType.LongText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)MySqlDbType.Guid, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}", "GetString") }, - { (int)MySqlDbType.String, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)MySqlDbType.VarString, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)MySqlDbType.VarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)MySqlDbType.Guid, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}", "GetString") }, + { (int)MySqlDbType.String, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)MySqlDbType.VarString, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)MySqlDbType.VarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)MySqlDbType.Set, ("(long?)", "long.Parse({0})", "{0}.ToInt64().ToString()", "Set", typeof(Enum), typeof(Enum), "{0}", "GetInt64") }, - { (int)MySqlDbType.Enum, ("(long?)", "long.Parse({0})", "{0}.ToInt64().ToString()", "Enum", typeof(Enum), typeof(Enum), "{0}", "GetInt64") }, + { (int)MySqlDbType.Set, ("(long?)", "long.Parse({0})", "{0}.ToInt64().ToString()", "Set", typeof(Enum), typeof(Enum), "{0}", "GetInt64") }, + { (int)MySqlDbType.Enum, ("(long?)", "long.Parse({0})", "{0}.ToInt64().ToString()", "Enum", typeof(Enum), typeof(Enum), "{0}", "GetInt64") }, - { (int)MySqlDbType.Geometry, ("(MygisGeometry)", "MygisGeometry.Parse({0}.Replace(StringifySplit, \"|\"))", "{0}.AsText().Replace(\"|\", StringifySplit)", "MygisGeometry", typeof(MygisGeometry), typeof(MygisGeometry), "{0}", "GetString") }, - }; + { (int)MySqlDbType.Geometry, ("(MygisGeometry)", "MygisGeometry.Parse({0}.Replace(StringifySplit, \"|\"))", "{0}.AsText().Replace(\"|\", StringifySplit)", "MygisGeometry", typeof(MygisGeometry), typeof(MygisGeometry), "{0}", "GetString") }, + }; - public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; - public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csParse : null; - public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csStringify : null; - public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; - public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeInfo : null; - public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeValue : null; - public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.dataReaderMethod : null; + public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; + public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csParse : null; + public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csStringify : null; + public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; + public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeInfo : null; + public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeValue : null; + public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.dataReaderMethod : null; - public List GetDatabases() { - var sql = @" select schema_name from information_schema.schemata where schema_name not in ('information_schema', 'mysql', 'performance_schema')"; - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); - } + public List GetDatabases() + { + var sql = @" select schema_name from information_schema.schemata where schema_name not in ('information_schema', 'mysql', 'performance_schema')"; + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); + } - public List GetTablesByDatabase(params string[] database2) { - var loc1 = new List(); - var loc2 = new Dictionary(); - var loc3 = new Dictionary>(); - var database = database2?.ToArray(); + public List GetTablesByDatabase(params string[] database2) + { + var loc1 = new List(); + var loc2 = new Dictionary(); + var loc3 = new Dictionary>(); + var database = database2?.ToArray(); - if (database == null || database.Any() == false) { - using (var conn = _orm.Ado.MasterPool.Get()) { - if (string.IsNullOrEmpty(conn.Value.Database)) return loc1; - database = new[] { conn.Value.Database }; - } - } - var databaseIn = string.Join(",", database.Select(a => _commonUtils.FormatSql("{0}", a))); - var sql = string.Format(@" + if (database == null || database.Any() == false) + { + using (var conn = _orm.Ado.MasterPool.Get()) + { + if (string.IsNullOrEmpty(conn.Value.Database)) return loc1; + database = new[] { conn.Value.Database }; + } + } + var databaseIn = string.Join(",", database.Select(a => _commonUtils.FormatSql("{0}", a))); + var sql = string.Format(@" select concat(a.table_schema, '.', a.table_name) 'id', a.table_schema 'schema', @@ -158,38 +167,41 @@ a.table_comment, a.table_type 'type' from information_schema.tables a where a.table_schema in ({0})", databaseIn); - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var loc6 = new List(); - var loc66 = new List(); - foreach (var row in ds) { - var table_id = string.Concat(row[0]); - var schema = string.Concat(row[1]); - var table = string.Concat(row[2]); - var comment = string.Concat(row[3]); - var type = string.Concat(row[4]) == "VIEW" ? DbTableType.VIEW : DbTableType.TABLE; - if (database.Length == 1) { - table_id = table_id.Substring(table_id.IndexOf('.') + 1); - schema = ""; - } - loc2.Add(table_id, new DbTableInfo { Id = table_id, Schema = schema, Name = table, Comment = comment, Type = type }); - loc3.Add(table_id, new Dictionary()); - switch (type) { - case DbTableType.TABLE: - case DbTableType.VIEW: - loc6.Add(table.Replace("'", "''")); - break; - case DbTableType.StoreProcedure: - loc66.Add(table.Replace("'", "''")); - break; - } - } - if (loc6.Count == 0) return loc1; - var loc8 = "'" + string.Join("','", loc6.ToArray()) + "'"; - var loc88 = "'" + string.Join("','", loc66.ToArray()) + "'"; + var loc6 = new List(); + var loc66 = new List(); + foreach (var row in ds) + { + var table_id = string.Concat(row[0]); + var schema = string.Concat(row[1]); + var table = string.Concat(row[2]); + var comment = string.Concat(row[3]); + var type = string.Concat(row[4]) == "VIEW" ? DbTableType.VIEW : DbTableType.TABLE; + if (database.Length == 1) + { + table_id = table_id.Substring(table_id.IndexOf('.') + 1); + schema = ""; + } + loc2.Add(table_id, new DbTableInfo { Id = table_id, Schema = schema, Name = table, Comment = comment, Type = type }); + loc3.Add(table_id, new Dictionary()); + switch (type) + { + case DbTableType.TABLE: + case DbTableType.VIEW: + loc6.Add(table.Replace("'", "''")); + break; + case DbTableType.StoreProcedure: + loc66.Add(table.Replace("'", "''")); + break; + } + } + if (loc6.Count == 0) return loc1; + var loc8 = "'" + string.Join("','", loc6.ToArray()) + "'"; + var loc88 = "'" + string.Join("','", loc66.ToArray()) + "'"; - sql = string.Format(@" + sql = string.Format(@" select concat(a.table_schema, '.', a.table_name), a.column_name, @@ -202,40 +214,43 @@ a.column_comment 'comment' from information_schema.columns a where a.table_schema in ({1}) and a.table_name in ({0}) ", loc8, databaseIn); - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - foreach (var row in ds) { - string table_id = string.Concat(row[0]); - string column = string.Concat(row[1]); - string type = string.Concat(row[2]); - //long max_length = long.Parse(string.Concat(row[3])); - string sqlType = string.Concat(row[4]); - var m_len = Regex.Match(sqlType, @"\w+\((\d+)"); - int max_length = m_len.Success ? int.Parse(m_len.Groups[1].Value) : -1; - bool is_nullable = string.Concat(row[5]) == "1"; - bool is_identity = string.Concat(row[6]) == "1"; - string comment = string.Concat(row[7]); - if (max_length == 0) max_length = -1; - if (database.Length == 1) { - table_id = table_id.Substring(table_id.IndexOf('.') + 1); - } - loc3[table_id].Add(column, new DbColumnInfo { - Name = column, - MaxLength = max_length, - IsIdentity = is_identity, - IsNullable = is_nullable, - IsPrimary = false, - DbTypeText = type, - DbTypeTextFull = sqlType, - Table = loc2[table_id], - Coment = comment - }); - loc3[table_id][column].DbType = this.GetDbType(loc3[table_id][column]); - loc3[table_id][column].CsType = this.GetCsTypeInfo(loc3[table_id][column]); - } + foreach (var row in ds) + { + string table_id = string.Concat(row[0]); + string column = string.Concat(row[1]); + string type = string.Concat(row[2]); + //long max_length = long.Parse(string.Concat(row[3])); + string sqlType = string.Concat(row[4]); + var m_len = Regex.Match(sqlType, @"\w+\((\d+)"); + int max_length = m_len.Success ? int.Parse(m_len.Groups[1].Value) : -1; + bool is_nullable = string.Concat(row[5]) == "1"; + bool is_identity = string.Concat(row[6]) == "1"; + string comment = string.Concat(row[7]); + if (max_length == 0) max_length = -1; + if (database.Length == 1) + { + table_id = table_id.Substring(table_id.IndexOf('.') + 1); + } + loc3[table_id].Add(column, new DbColumnInfo + { + Name = column, + MaxLength = max_length, + IsIdentity = is_identity, + IsNullable = is_nullable, + IsPrimary = false, + DbTypeText = type, + DbTypeTextFull = sqlType, + Table = loc2[table_id], + Coment = comment + }); + loc3[table_id][column].DbType = this.GetDbType(loc3[table_id][column]); + loc3[table_id][column].CsType = this.GetCsTypeInfo(loc3[table_id][column]); + } - sql = string.Format(@" + sql = string.Format(@" select concat(a.constraint_schema, '.', a.table_name) 'table_id', a.column_name, @@ -247,53 +262,59 @@ case when a.constraint_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey', from information_schema.key_column_usage a where a.constraint_schema in ({1}) and a.table_name in ({0}) and isnull(position_in_unique_constraint) ", loc8, databaseIn); - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var indexColumns = new Dictionary>>(); - var uniqueColumns = new Dictionary>>(); - foreach (var row in ds) { - string table_id = string.Concat(row[0]); - string column = string.Concat(row[1]); - string index_id = string.Concat(row[2]); - bool is_unique = string.Concat(row[3]) == "1"; - bool is_primary_key = string.Concat(row[4]) == "1"; - bool is_clustered = string.Concat(row[5]) == "1"; - int is_desc = int.Parse(string.Concat(row[6])); - if (database.Length == 1) { - table_id = table_id.Substring(table_id.IndexOf('.') + 1); - } - if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; - var loc9 = loc3[table_id][column]; - if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; + var indexColumns = new Dictionary>>(); + var uniqueColumns = new Dictionary>>(); + foreach (var row in ds) + { + string table_id = string.Concat(row[0]); + string column = string.Concat(row[1]); + string index_id = string.Concat(row[2]); + bool is_unique = string.Concat(row[3]) == "1"; + bool is_primary_key = string.Concat(row[4]) == "1"; + bool is_clustered = string.Concat(row[5]) == "1"; + int is_desc = int.Parse(string.Concat(row[6])); + if (database.Length == 1) + { + table_id = table_id.Substring(table_id.IndexOf('.') + 1); + } + if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; + var loc9 = loc3[table_id][column]; + if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; - Dictionary> loc10 = null; - List loc11 = null; - if (!indexColumns.TryGetValue(table_id, out loc10)) - indexColumns.Add(table_id, loc10 = new Dictionary>()); - if (!loc10.TryGetValue(index_id, out loc11)) - loc10.Add(index_id, loc11 = new List()); - loc11.Add(loc9); - if (is_unique && !is_primary_key) { - if (!uniqueColumns.TryGetValue(table_id, out loc10)) - uniqueColumns.Add(table_id, loc10 = new Dictionary>()); - if (!loc10.TryGetValue(index_id, out loc11)) - loc10.Add(index_id, loc11 = new List()); - loc11.Add(loc9); - } - } - foreach (string table_id in indexColumns.Keys) { - foreach (var column in indexColumns[table_id]) - loc2[table_id].IndexesDict.Add(column.Key, column.Value); - } - foreach (string table_id in uniqueColumns.Keys) { - foreach (var column in uniqueColumns[table_id]) { - column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); - loc2[table_id].UniquesDict.Add(column.Key, column.Value); - } - } + Dictionary> loc10 = null; + List loc11 = null; + if (!indexColumns.TryGetValue(table_id, out loc10)) + indexColumns.Add(table_id, loc10 = new Dictionary>()); + if (!loc10.TryGetValue(index_id, out loc11)) + loc10.Add(index_id, loc11 = new List()); + loc11.Add(loc9); + if (is_unique && !is_primary_key) + { + if (!uniqueColumns.TryGetValue(table_id, out loc10)) + uniqueColumns.Add(table_id, loc10 = new Dictionary>()); + if (!loc10.TryGetValue(index_id, out loc11)) + loc10.Add(index_id, loc11 = new List()); + loc11.Add(loc9); + } + } + foreach (string table_id in indexColumns.Keys) + { + foreach (var column in indexColumns[table_id]) + loc2[table_id].IndexesDict.Add(column.Key, column.Value); + } + foreach (string table_id in uniqueColumns.Keys) + { + foreach (var column in uniqueColumns[table_id]) + { + column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); + loc2[table_id].UniquesDict.Add(column.Key, column.Value); + } + } - sql = string.Format(@" + sql = string.Format(@" select concat(a.constraint_schema, '.', a.table_name) 'table_id', a.column_name, @@ -304,80 +325,91 @@ a.referenced_column_name 'ref_column' from information_schema.key_column_usage a where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(position_in_unique_constraint) ", loc8, databaseIn); - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var fkColumns = new Dictionary>(); - foreach (var row in ds) { - string table_id = string.Concat(row[0]); - string column = string.Concat(row[1]); - string fk_id = string.Concat(row[2]); - string ref_table_id = string.Concat(row[3]); - bool is_foreign_key = string.Concat(row[4]) == "1"; - string referenced_column = string.Concat(row[5]); - if (database.Length == 1) { - table_id = table_id.Substring(table_id.IndexOf('.') + 1); - ref_table_id = ref_table_id.Substring(ref_table_id.IndexOf('.') + 1); - } - if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; - var loc9 = loc3[table_id][column]; - if (loc2.ContainsKey(ref_table_id) == false) continue; - var loc10 = loc2[ref_table_id]; - var loc11 = loc3[ref_table_id][referenced_column]; + var fkColumns = new Dictionary>(); + foreach (var row in ds) + { + string table_id = string.Concat(row[0]); + string column = string.Concat(row[1]); + string fk_id = string.Concat(row[2]); + string ref_table_id = string.Concat(row[3]); + bool is_foreign_key = string.Concat(row[4]) == "1"; + string referenced_column = string.Concat(row[5]); + if (database.Length == 1) + { + table_id = table_id.Substring(table_id.IndexOf('.') + 1); + ref_table_id = ref_table_id.Substring(ref_table_id.IndexOf('.') + 1); + } + if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; + var loc9 = loc3[table_id][column]; + if (loc2.ContainsKey(ref_table_id) == false) continue; + var loc10 = loc2[ref_table_id]; + var loc11 = loc3[ref_table_id][referenced_column]; - Dictionary loc12 = null; - DbForeignInfo loc13 = null; - if (!fkColumns.TryGetValue(table_id, out loc12)) - fkColumns.Add(table_id, loc12 = new Dictionary()); - if (!loc12.TryGetValue(fk_id, out loc13)) - loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[table_id], ReferencedTable = loc10 }); - loc13.Columns.Add(loc9); - loc13.ReferencedColumns.Add(loc11); - } - foreach (var table_id in fkColumns.Keys) - foreach (var fk in fkColumns[table_id]) - loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); + Dictionary loc12 = null; + DbForeignInfo loc13 = null; + if (!fkColumns.TryGetValue(table_id, out loc12)) + fkColumns.Add(table_id, loc12 = new Dictionary()); + if (!loc12.TryGetValue(fk_id, out loc13)) + loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[table_id], ReferencedTable = loc10 }); + loc13.Columns.Add(loc9); + loc13.ReferencedColumns.Add(loc11); + } + foreach (var table_id in fkColumns.Keys) + foreach (var fk in fkColumns[table_id]) + loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); - foreach (var table_id in loc3.Keys) { - foreach (var loc5 in loc3[table_id].Values) { - loc2[table_id].Columns.Add(loc5); - if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); - if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); - } - } - foreach (var loc4 in loc2.Values) { - if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) { - foreach (var loc5 in loc4.UniquesDict.First().Value) { - loc5.IsPrimary = true; - loc4.Primarys.Add(loc5); - } - } - loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); - loc4.Columns.Sort((c1, c2) => { - int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); - if (compare == 0) { - bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); - bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); - compare = b2.CompareTo(b1); - } - if (compare == 0) compare = c1.Name.CompareTo(c2.Name); - return compare; - }); - loc1.Add(loc4); - } - loc1.Sort((t1, t2) => { - var ret = t1.Schema.CompareTo(t2.Schema); - if (ret == 0) ret = t1.Name.CompareTo(t2.Name); - return ret; - }); + foreach (var table_id in loc3.Keys) + { + foreach (var loc5 in loc3[table_id].Values) + { + loc2[table_id].Columns.Add(loc5); + if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); + if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); + } + } + foreach (var loc4 in loc2.Values) + { + if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) + { + foreach (var loc5 in loc4.UniquesDict.First().Value) + { + loc5.IsPrimary = true; + loc4.Primarys.Add(loc5); + } + } + loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); + loc4.Columns.Sort((c1, c2) => + { + int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); + if (compare == 0) + { + bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); + bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); + compare = b2.CompareTo(b1); + } + if (compare == 0) compare = c1.Name.CompareTo(c2.Name); + return compare; + }); + loc1.Add(loc4); + } + loc1.Sort((t1, t2) => + { + var ret = t1.Schema.CompareTo(t2.Schema); + if (ret == 0) ret = t1.Name.CompareTo(t2.Name); + return ret; + }); - loc2.Clear(); - loc3.Clear(); - return loc1; - } + loc2.Clear(); + loc3.Clear(); + return loc1; + } - public List GetEnumsByDatabase(params string[] database) { - return new List(); - } - } + public List GetEnumsByDatabase(params string[] database) + { + return new List(); + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.MySql/MySqlExpression.cs b/Providers/FreeSql.Provider.MySql/MySqlExpression.cs index 1f67704f..10b93e5a 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlExpression.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlExpression.cs @@ -7,392 +7,447 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.MySql { - class MySqlExpression : CommonExpression { +namespace FreeSql.MySql +{ + class MySqlExpression : CommonExpression + { - public MySqlExpression(CommonUtils common) : base(common) { } + public MySqlExpression(CommonUtils common) : base(common) { } - public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.NodeType) { - case ExpressionType.Convert: - var operandExp = (exp as UnaryExpression)?.Operand; - var gentype = exp.Type.NullableTypeOrThis(); - if (gentype != operandExp.Type.NullableTypeOrThis()) { - switch (gentype.ToString()) { - case "System.Boolean": return $"({getExp(operandExp)} not in ('0','false'))"; - case "System.Byte": return $"cast({getExp(operandExp)} as unsigned)"; - case "System.Char": return $"substr(cast({getExp(operandExp)} as char), 1, 1)"; - case "System.DateTime": return $"cast({getExp(operandExp)} as datetime)"; - case "System.Decimal": return $"cast({getExp(operandExp)} as decimal(36,18))"; - case "System.Double": return $"cast({getExp(operandExp)} as decimal(32,16))"; - case "System.Int16": - case "System.Int32": - case "System.Int64": - case "System.SByte": return $"cast({getExp(operandExp)} as signed)"; - case "System.Single": return $"cast({getExp(operandExp)} as decimal(14,7))"; - case "System.String": return $"cast({getExp(operandExp)} as char)"; - case "System.UInt16": - case "System.UInt32": - case "System.UInt64": return $"cast({getExp(operandExp)} as unsigned)"; - case "System.Guid": return $"substr(cast({getExp(operandExp)} as char), 1, 36)"; - } - } - break; - case ExpressionType.Call: - var callExp = exp as MethodCallExpression; + public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.NodeType) + { + case ExpressionType.Convert: + var operandExp = (exp as UnaryExpression)?.Operand; + var gentype = exp.Type.NullableTypeOrThis(); + if (gentype != operandExp.Type.NullableTypeOrThis()) + { + switch (gentype.ToString()) + { + case "System.Boolean": return $"({getExp(operandExp)} not in ('0','false'))"; + case "System.Byte": return $"cast({getExp(operandExp)} as unsigned)"; + case "System.Char": return $"substr(cast({getExp(operandExp)} as char), 1, 1)"; + case "System.DateTime": return $"cast({getExp(operandExp)} as datetime)"; + case "System.Decimal": return $"cast({getExp(operandExp)} as decimal(36,18))"; + case "System.Double": return $"cast({getExp(operandExp)} as decimal(32,16))"; + case "System.Int16": + case "System.Int32": + case "System.Int64": + case "System.SByte": return $"cast({getExp(operandExp)} as signed)"; + case "System.Single": return $"cast({getExp(operandExp)} as decimal(14,7))"; + case "System.String": return $"cast({getExp(operandExp)} as char)"; + case "System.UInt16": + case "System.UInt32": + case "System.UInt64": return $"cast({getExp(operandExp)} as unsigned)"; + case "System.Guid": return $"substr(cast({getExp(operandExp)} as char), 1, 36)"; + } + } + break; + case ExpressionType.Call: + var callExp = exp as MethodCallExpression; - switch (callExp.Method.Name) { - case "Parse": - case "TryParse": - switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) { - case "System.Boolean": return $"({getExp(callExp.Arguments[0])} not in ('0','false'))"; - case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as unsigned)"; - case "System.Char": return $"substr(cast({getExp(callExp.Arguments[0])} as char), 1, 1)"; - case "System.DateTime": return $"cast({getExp(callExp.Arguments[0])} as datetime)"; - case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as decimal(36,18))"; - case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as decimal(32,16))"; - case "System.Int16": - case "System.Int32": - case "System.Int64": - case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as signed)"; - case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as decimal(14,7))"; - case "System.UInt16": - case "System.UInt32": - case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as unsigned)"; - case "System.Guid": return $"substr(cast({getExp(callExp.Arguments[0])} as char), 1, 36)"; - } - break; - case "NewGuid": - break; - case "Next": - if (callExp.Object?.Type == typeof(Random)) return "cast(rand()*1000000000 as signed)"; - break; - case "NextDouble": - if (callExp.Object?.Type == typeof(Random)) return "rand()"; - break; - case "Random": - if (callExp.Method.DeclaringType.IsNumberType()) return "rand()"; - break; - case "ToString": - if (callExp.Object != null) return $"cast({getExp(callExp.Object)} as char)"; - break; - } + switch (callExp.Method.Name) + { + case "Parse": + case "TryParse": + switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) + { + case "System.Boolean": return $"({getExp(callExp.Arguments[0])} not in ('0','false'))"; + case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as unsigned)"; + case "System.Char": return $"substr(cast({getExp(callExp.Arguments[0])} as char), 1, 1)"; + case "System.DateTime": return $"cast({getExp(callExp.Arguments[0])} as datetime)"; + case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as decimal(36,18))"; + case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as decimal(32,16))"; + case "System.Int16": + case "System.Int32": + case "System.Int64": + case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as signed)"; + case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as decimal(14,7))"; + case "System.UInt16": + case "System.UInt32": + case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as unsigned)"; + case "System.Guid": return $"substr(cast({getExp(callExp.Arguments[0])} as char), 1, 36)"; + } + break; + case "NewGuid": + break; + case "Next": + if (callExp.Object?.Type == typeof(Random)) return "cast(rand()*1000000000 as signed)"; + break; + case "NextDouble": + if (callExp.Object?.Type == typeof(Random)) return "rand()"; + break; + case "Random": + if (callExp.Method.DeclaringType.IsNumberType()) return "rand()"; + break; + case "ToString": + if (callExp.Object != null) return $"cast({getExp(callExp.Object)} as char)"; + break; + } - var objExp = callExp.Object; - var objType = objExp?.Type; - if (objType?.FullName == "System.Byte[]") return null; + var objExp = callExp.Object; + var objType = objExp?.Type; + if (objType?.FullName == "System.Byte[]") return null; - var argIndex = 0; - if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) { - objExp = callExp.Arguments.FirstOrDefault(); - objType = objExp?.Type; - argIndex++; - } - if (objType == null) objType = callExp.Method.DeclaringType; - if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) { - var left = objExp == null ? null : getExp(objExp); - switch (callExp.Method.Name) { - case "Contains": - //判断 in - return $"({getExp(callExp.Arguments[argIndex])}) in {left}"; - } - } - break; - case ExpressionType.NewArrayInit: - var arrExp = exp as NewArrayExpression; - var arrSb = new StringBuilder(); - arrSb.Append("("); - for (var a = 0; a < arrExp.Expressions.Count; a++) { - if (a > 0) arrSb.Append(","); - arrSb.Append(getExp(arrExp.Expressions[a])); - } - if (arrSb.Length == 1) arrSb.Append("NULL"); - return arrSb.Append(")").ToString(); - case ExpressionType.ListInit: - var listExp = exp as ListInitExpression; - var listSb = new StringBuilder(); - listSb.Append("("); - for (var a = 0; a < listExp.Initializers.Count; a++) { - if (listExp.Initializers[a].Arguments.Any() == false) continue; - if (a > 0) listSb.Append(","); - listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); - } - if (listSb.Length == 1) listSb.Append("NULL"); - return listSb.Append(")").ToString(); - case ExpressionType.New: - var newExp = exp as NewExpression; - if (typeof(IList).IsAssignableFrom(newExp.Type)) { - if (newExp.Arguments.Count == 0) return "(NULL)"; - if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; - return getExp(newExp.Arguments[0]); - } - return null; - } - return null; - } + var argIndex = 0; + if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) + { + objExp = callExp.Arguments.FirstOrDefault(); + objType = objExp?.Type; + argIndex++; + } + if (objType == null) objType = callExp.Method.DeclaringType; + if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) + { + var left = objExp == null ? null : getExp(objExp); + switch (callExp.Method.Name) + { + case "Contains": + //判断 in + return $"({getExp(callExp.Arguments[argIndex])}) in {left}"; + } + } + break; + case ExpressionType.NewArrayInit: + var arrExp = exp as NewArrayExpression; + var arrSb = new StringBuilder(); + arrSb.Append("("); + for (var a = 0; a < arrExp.Expressions.Count; a++) + { + if (a > 0) arrSb.Append(","); + arrSb.Append(getExp(arrExp.Expressions[a])); + } + if (arrSb.Length == 1) arrSb.Append("NULL"); + return arrSb.Append(")").ToString(); + case ExpressionType.ListInit: + var listExp = exp as ListInitExpression; + var listSb = new StringBuilder(); + listSb.Append("("); + for (var a = 0; a < listExp.Initializers.Count; a++) + { + if (listExp.Initializers[a].Arguments.Any() == false) continue; + if (a > 0) listSb.Append(","); + listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); + } + if (listSb.Length == 1) listSb.Append("NULL"); + return listSb.Append(")").ToString(); + case ExpressionType.New: + var newExp = exp as NewExpression; + if (typeof(IList).IsAssignableFrom(newExp.Type)) + { + if (newExp.Arguments.Count == 0) return "(NULL)"; + if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; + return getExp(newExp.Arguments[0]); + } + return null; + } + return null; + } - public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Empty": return "''"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Length": return $"char_length({left})"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Now": return "now()"; - case "UtcNow": return "utc_timestamp()"; - case "Today": return "curdate()"; - case "MinValue": return "cast('0001/1/1 0:00:00' as datetime)"; - case "MaxValue": return "cast('9999/12/31 23:59:59' as datetime)"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Date": return $"cast(date_format({left},'%Y-%m-%d') as datetime)"; - case "TimeOfDay": return $"timestampdiff(microsecond, date_format({left},'%Y-%m-%d'), {left})"; - case "DayOfWeek": return $"(dayofweek({left})-1)"; - case "Day": return $"dayofmonth({left})"; - case "DayOfYear": return $"dayofyear({left})"; - case "Month": return $"month({left})"; - case "Year": return $"year({left})"; - case "Hour": return $"hour({left})"; - case "Minute": return $"minute({left})"; - case "Second": return $"second({left})"; - case "Millisecond": return $"floor(microsecond({left})/1000)"; - case "Ticks": return $"(timestampdiff(microsecond, '0001-1-1', {left})*10)"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Zero": return "0"; - case "MinValue": return "-922337203685477580"; //微秒 Ticks / 10 - case "MaxValue": return "922337203685477580"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Days": return $"(({left}) div {(long)1000000 * 60 * 60 * 24})"; - case "Hours": return $"(({left}) div {(long)1000000 * 60 * 60} mod 24)"; - case "Milliseconds": return $"(({left}) div 1000 mod 1000)"; - case "Minutes": return $"(({left}) div {(long)1000000 * 60} mod 60)"; - case "Seconds": return $"(({left}) div 1000000 mod 60)"; - case "Ticks": return $"(({left}) * 10)"; - case "TotalDays": return $"(({left}) / {(long)1000000 * 60 * 60 * 24})"; - case "TotalHours": return $"(({left}) / {(long)1000000 * 60 * 60})"; - case "TotalMilliseconds": return $"(({left}) / 1000)"; - case "TotalMinutes": return $"(({left}) / {(long)1000000 * 60})"; - case "TotalSeconds": return $"(({left}) / 1000000)"; - } - return null; - } + public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Empty": return "''"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Length": return $"char_length({left})"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Now": return "now()"; + case "UtcNow": return "utc_timestamp()"; + case "Today": return "curdate()"; + case "MinValue": return "cast('0001/1/1 0:00:00' as datetime)"; + case "MaxValue": return "cast('9999/12/31 23:59:59' as datetime)"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Date": return $"cast(date_format({left},'%Y-%m-%d') as datetime)"; + case "TimeOfDay": return $"timestampdiff(microsecond, date_format({left},'%Y-%m-%d'), {left})"; + case "DayOfWeek": return $"(dayofweek({left})-1)"; + case "Day": return $"dayofmonth({left})"; + case "DayOfYear": return $"dayofyear({left})"; + case "Month": return $"month({left})"; + case "Year": return $"year({left})"; + case "Hour": return $"hour({left})"; + case "Minute": return $"minute({left})"; + case "Second": return $"second({left})"; + case "Millisecond": return $"floor(microsecond({left})/1000)"; + case "Ticks": return $"(timestampdiff(microsecond, '0001-1-1', {left})*10)"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Zero": return "0"; + case "MinValue": return "-922337203685477580"; //微秒 Ticks / 10 + case "MaxValue": return "922337203685477580"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Days": return $"(({left}) div {(long)1000000 * 60 * 60 * 24})"; + case "Hours": return $"(({left}) div {(long)1000000 * 60 * 60} mod 24)"; + case "Milliseconds": return $"(({left}) div 1000 mod 1000)"; + case "Minutes": return $"(({left}) div {(long)1000000 * 60} mod 60)"; + case "Seconds": return $"(({left}) div 1000000 mod 60)"; + case "Ticks": return $"(({left}) * 10)"; + case "TotalDays": return $"(({left}) / {(long)1000000 * 60 * 60 * 24})"; + case "TotalHours": return $"(({left}) / {(long)1000000 * 60 * 60})"; + case "TotalMilliseconds": return $"(({left}) / 1000)"; + case "TotalMinutes": return $"(({left}) / {(long)1000000 * 60})"; + case "TotalSeconds": return $"(({left}) / 1000000)"; + } + return null; + } - public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "IsNullOrEmpty": - var arg1 = getExp(exp.Arguments[0]); - return $"({arg1} is null or {arg1} = '')"; - case "Concat": - return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); - } - } else { - var left = getExp(exp.Object); - switch (exp.Method.Name) { - case "StartsWith": - case "EndsWith": - case "Contains": - var args0Value = getExp(exp.Arguments[0]); - if (args0Value == "NULL") return $"({left}) IS NULL"; - if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"concat({args0Value}, '%')")}"; - if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"concat('%', {args0Value})")}"; - if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; - return $"({left}) LIKE concat('%', {args0Value}, '%')"; - case "ToLower": return $"lower({left})"; - case "ToUpper": return $"upper({left})"; - case "Substring": - var substrArgs1 = getExp(exp.Arguments[0]); - if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); - else substrArgs1 += "+1"; - if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; - return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; - case "IndexOf": - var indexOfFindStr = getExp(exp.Arguments[0]); - if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") { - var locateArgs1 = getExp(exp.Arguments[1]); - if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); - else locateArgs1 += "+1"; - return $"(locate({left}, {indexOfFindStr}, {locateArgs1})-1)"; - } - return $"(locate({left}, {indexOfFindStr})-1)"; - case "PadLeft": - if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})"; - return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "PadRight": - if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})"; - return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Trim": - case "TrimStart": - case "TrimEnd": - if (exp.Arguments.Count == 0) { - if (exp.Method.Name == "Trim") return $"trim({left})"; - if (exp.Method.Name == "TrimStart") return $"ltrim({left})"; - if (exp.Method.Name == "TrimEnd") return $"rtrim({left})"; - } - foreach (var argsTrim02 in exp.Arguments) { - var argsTrim01s = new[] { argsTrim02 }; - if (argsTrim02.NodeType == ExpressionType.NewArrayInit) { - var arritem = argsTrim02 as NewArrayExpression; - argsTrim01s = arritem.Expressions.ToArray(); - } - foreach (var argsTrim01 in argsTrim01s) { - if (exp.Method.Name == "Trim") left = $"trim({getExp(argsTrim01)} from {left})"; - if (exp.Method.Name == "TrimStart") left = $"trim(leading {getExp(argsTrim01)} from {left})"; - if (exp.Method.Name == "TrimEnd") left = $"trim(trailing {getExp(argsTrim01)} from {left})"; - } - } - return left; - case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "CompareTo": return $"strcmp({left}, {getExp(exp.Arguments[0])})"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - } - } - throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.Method.Name) { - case "Abs": return $"abs({getExp(exp.Arguments[0])})"; - case "Sign": return $"sign({getExp(exp.Arguments[0])})"; - case "Floor": return $"floor({getExp(exp.Arguments[0])})"; - case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})"; - case "Round": - if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - return $"round({getExp(exp.Arguments[0])})"; - case "Exp": return $"exp({getExp(exp.Arguments[0])})"; - case "Log": return $"log({getExp(exp.Arguments[0])})"; - case "Log10": return $"log10({getExp(exp.Arguments[0])})"; - case "Pow": return $"pow({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; - case "Cos": return $"cos({getExp(exp.Arguments[0])})"; - case "Sin": return $"sin({getExp(exp.Arguments[0])})"; - case "Tan": return $"tan({getExp(exp.Arguments[0])})"; - case "Acos": return $"acos({getExp(exp.Arguments[0])})"; - case "Asin": return $"asin({getExp(exp.Arguments[0])})"; - case "Atan": return $"atan({getExp(exp.Arguments[0])})"; - case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Truncate": return $"truncate({getExp(exp.Arguments[0])}, 0)"; - } - throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"({getExp(exp.Arguments[0])} - ({getExp(exp.Arguments[1])}))"; - case "DaysInMonth": return $"dayofmonth(last_day(concat({getExp(exp.Arguments[0])}, '-', {getExp(exp.Arguments[1])}, '-01')))"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "IsNullOrEmpty": + var arg1 = getExp(exp.Arguments[0]); + return $"({arg1} is null or {arg1} = '')"; + case "Concat": + return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); + } + } + else + { + var left = getExp(exp.Object); + switch (exp.Method.Name) + { + case "StartsWith": + case "EndsWith": + case "Contains": + var args0Value = getExp(exp.Arguments[0]); + if (args0Value == "NULL") return $"({left}) IS NULL"; + if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"concat({args0Value}, '%')")}"; + if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"concat('%', {args0Value})")}"; + if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; + return $"({left}) LIKE concat('%', {args0Value}, '%')"; + case "ToLower": return $"lower({left})"; + case "ToUpper": return $"upper({left})"; + case "Substring": + var substrArgs1 = getExp(exp.Arguments[0]); + if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); + else substrArgs1 += "+1"; + if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; + return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; + case "IndexOf": + var indexOfFindStr = getExp(exp.Arguments[0]); + if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") + { + var locateArgs1 = getExp(exp.Arguments[1]); + if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); + else locateArgs1 += "+1"; + return $"(locate({left}, {indexOfFindStr}, {locateArgs1})-1)"; + } + return $"(locate({left}, {indexOfFindStr})-1)"; + case "PadLeft": + if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})"; + return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "PadRight": + if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})"; + return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Trim": + case "TrimStart": + case "TrimEnd": + if (exp.Arguments.Count == 0) + { + if (exp.Method.Name == "Trim") return $"trim({left})"; + if (exp.Method.Name == "TrimStart") return $"ltrim({left})"; + if (exp.Method.Name == "TrimEnd") return $"rtrim({left})"; + } + foreach (var argsTrim02 in exp.Arguments) + { + var argsTrim01s = new[] { argsTrim02 }; + if (argsTrim02.NodeType == ExpressionType.NewArrayInit) + { + var arritem = argsTrim02 as NewArrayExpression; + argsTrim01s = arritem.Expressions.ToArray(); + } + foreach (var argsTrim01 in argsTrim01s) + { + if (exp.Method.Name == "Trim") left = $"trim({getExp(argsTrim01)} from {left})"; + if (exp.Method.Name == "TrimStart") left = $"trim(leading {getExp(argsTrim01)} from {left})"; + if (exp.Method.Name == "TrimEnd") left = $"trim(trailing {getExp(argsTrim01)} from {left})"; + } + } + return left; + case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "CompareTo": return $"strcmp({left}, {getExp(exp.Arguments[0])})"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + } + } + throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.Method.Name) + { + case "Abs": return $"abs({getExp(exp.Arguments[0])})"; + case "Sign": return $"sign({getExp(exp.Arguments[0])})"; + case "Floor": return $"floor({getExp(exp.Arguments[0])})"; + case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})"; + case "Round": + if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + return $"round({getExp(exp.Arguments[0])})"; + case "Exp": return $"exp({getExp(exp.Arguments[0])})"; + case "Log": return $"log({getExp(exp.Arguments[0])})"; + case "Log10": return $"log10({getExp(exp.Arguments[0])})"; + case "Pow": return $"pow({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; + case "Cos": return $"cos({getExp(exp.Arguments[0])})"; + case "Sin": return $"sin({getExp(exp.Arguments[0])})"; + case "Tan": return $"tan({getExp(exp.Arguments[0])})"; + case "Acos": return $"acos({getExp(exp.Arguments[0])})"; + case "Asin": return $"asin({getExp(exp.Arguments[0])})"; + case "Atan": return $"atan({getExp(exp.Arguments[0])})"; + case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Truncate": return $"truncate({getExp(exp.Arguments[0])}, 0)"; + } + throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"({getExp(exp.Arguments[0])} - ({getExp(exp.Arguments[1])}))"; + case "DaysInMonth": return $"dayofmonth(last_day(concat({getExp(exp.Arguments[0])}, '-', {getExp(exp.Arguments[1])}, '-01')))"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "IsLeapYear": - var isLeapYearArgs1 = getExp(exp.Arguments[0]); - return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)"; + case "IsLeapYear": + var isLeapYearArgs1 = getExp(exp.Arguments[0]); + return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)"; - case "Parse": return $"cast({getExp(exp.Arguments[0])} as datetime)"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as datetime)"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"date_add({left}, interval ({args1}) microsecond)"; - case "AddDays": return $"date_add({left}, interval ({args1}) day)"; - case "AddHours": return $"date_add({left}, interval ({args1}) hour)"; - case "AddMilliseconds": return $"date_add({left}, interval ({args1})*1000 microsecond)"; - case "AddMinutes": return $"date_add({left}, interval ({args1}) minute)"; - case "AddMonths": return $"date_add({left}, interval ({args1}) month)"; - case "AddSeconds": return $"date_add({left}, interval ({args1}) second)"; - case "AddTicks": return $"date_add({left}, interval ({args1})/10 microsecond)"; - case "AddYears": return $"date_add({left}, interval ({args1}) year)"; - case "Subtract": - switch((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) { - case "System.DateTime": return $"timestampdiff(microsecond, {args1}, {left})"; - case "System.TimeSpan": return $"date_sub({left}, interval ({args1}) microsecond)"; - } - break; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"timestampdiff(microsecond,{args1},{left})"; - case "ToString": return $"date_format({left}, '%Y-%m-%d %H:%i:%s.%f')"; - } - } - throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "FromDays": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60 * 24})"; - case "FromHours": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60})"; - case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})*1000)"; - case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60})"; - case "FromSeconds": return $"(({getExp(exp.Arguments[0])})*1000000)"; - case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10)"; - case "Parse": return $"cast({getExp(exp.Arguments[0])} as signed)"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as signed)"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"({left}+{args1})"; - case "Subtract": return $"({left}-({args1}))"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))"; - case "ToString": return $"cast({left} as char)"; - } - } - throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))"; - case "ToByte": return $"cast({getExp(exp.Arguments[0])} as unsigned)"; - case "ToChar": return $"substr(cast({getExp(exp.Arguments[0])} as char), 1, 1)"; - case "ToDateTime": return $"cast({getExp(exp.Arguments[0])} as datetime)"; - case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))"; - case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as decimal(32,16))"; - case "ToInt16": - case "ToInt32": - case "ToInt64": - case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as signed)"; - case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as decimal(14,7))"; - case "ToString": return $"cast({getExp(exp.Arguments[0])} as char)"; - case "ToUInt16": - case "ToUInt32": - case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as unsigned)"; - } - } - throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); - } - } + case "Parse": return $"cast({getExp(exp.Arguments[0])} as datetime)"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as datetime)"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"date_add({left}, interval ({args1}) microsecond)"; + case "AddDays": return $"date_add({left}, interval ({args1}) day)"; + case "AddHours": return $"date_add({left}, interval ({args1}) hour)"; + case "AddMilliseconds": return $"date_add({left}, interval ({args1})*1000 microsecond)"; + case "AddMinutes": return $"date_add({left}, interval ({args1}) minute)"; + case "AddMonths": return $"date_add({left}, interval ({args1}) month)"; + case "AddSeconds": return $"date_add({left}, interval ({args1}) second)"; + case "AddTicks": return $"date_add({left}, interval ({args1})/10 microsecond)"; + case "AddYears": return $"date_add({left}, interval ({args1}) year)"; + case "Subtract": + switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) + { + case "System.DateTime": return $"timestampdiff(microsecond, {args1}, {left})"; + case "System.TimeSpan": return $"date_sub({left}, interval ({args1}) microsecond)"; + } + break; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"timestampdiff(microsecond,{args1},{left})"; + case "ToString": return $"date_format({left}, '%Y-%m-%d %H:%i:%s.%f')"; + } + } + throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + case "FromDays": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60 * 24})"; + case "FromHours": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60})"; + case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})*1000)"; + case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60})"; + case "FromSeconds": return $"(({getExp(exp.Arguments[0])})*1000000)"; + case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10)"; + case "Parse": return $"cast({getExp(exp.Arguments[0])} as signed)"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as signed)"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"({left}+{args1})"; + case "Subtract": return $"({left}-({args1}))"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))"; + case "ToString": return $"cast({left} as char)"; + } + } + throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))"; + case "ToByte": return $"cast({getExp(exp.Arguments[0])} as unsigned)"; + case "ToChar": return $"substr(cast({getExp(exp.Arguments[0])} as char), 1, 1)"; + case "ToDateTime": return $"cast({getExp(exp.Arguments[0])} as datetime)"; + case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))"; + case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as decimal(32,16))"; + case "ToInt16": + case "ToInt32": + case "ToInt64": + case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as signed)"; + case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as decimal(14,7))"; + case "ToString": return $"cast({getExp(exp.Arguments[0])} as char)"; + case "ToUInt16": + case "ToUInt32": + case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as unsigned)"; + } + } + throw new Exception($"MySqlExpression 未实现函数表达式 {exp} 解析"); + } + } } diff --git a/Providers/FreeSql.Provider.MySql/MySqlExtensions.cs b/Providers/FreeSql.Provider.MySql/MySqlExtensions.cs index ad1bf1f1..38857891 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlExtensions.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlExtensions.cs @@ -1,11 +1,12 @@ -public static partial class FreeSqlGlobalExtensions { +public static partial class FreeSqlGlobalExtensions +{ - /// - /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 - /// - /// - /// - /// - public static string FormatMySql(this string that, params object[] args) => _mysqlAdo.Addslashes(that, args); - static FreeSql.MySql.MySqlAdo _mysqlAdo = new FreeSql.MySql.MySqlAdo(); + /// + /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 + /// + /// + /// + /// + public static string FormatMySql(this string that, params object[] args) => _mysqlAdo.Addslashes(that, args); + static FreeSql.MySql.MySqlAdo _mysqlAdo = new FreeSql.MySql.MySqlAdo(); } diff --git a/Providers/FreeSql.Provider.MySql/MySqlProvider.cs b/Providers/FreeSql.Provider.MySql/MySqlProvider.cs index 461274fc..f53a0ebe 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlProvider.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlProvider.cs @@ -6,72 +6,80 @@ using System.Collections.Generic; using System.Data.Common; using System.Linq.Expressions; -namespace FreeSql.MySql { +namespace FreeSql.MySql +{ - public class MySqlProvider : IFreeSql { + public class MySqlProvider : IFreeSql + { - static MySqlProvider() { - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisPoint)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisLineString)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisPolygon)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisMultiPoint)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisMultiLineString)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisMultiPolygon)] = true; + static MySqlProvider() + { + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisPoint)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisLineString)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisPolygon)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisMultiPoint)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisMultiLineString)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(MygisMultiPolygon)] = true; - var MethodMygisGeometryParse = typeof(MygisGeometry).GetMethod("Parse", new[] { typeof(string) }); - Utils.GetDataReaderValueBlockExpressionSwitchTypeFullName.Add((LabelTarget returnTarget, Expression valueExp, string typeFullName) => { - switch (typeFullName) { - case "MygisPoint": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisPoint))); - case "MygisLineString": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisLineString))); - case "MygisPolygon": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisPolygon))); - case "MygisMultiPoint": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisMultiPoint))); - case "MygisMultiLineString": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisMultiLineString))); - case "MygisMultiPolygon": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisMultiPolygon))); - } - return null; - }); - } + var MethodMygisGeometryParse = typeof(MygisGeometry).GetMethod("Parse", new[] { typeof(string) }); + Utils.GetDataReaderValueBlockExpressionSwitchTypeFullName.Add((LabelTarget returnTarget, Expression valueExp, string typeFullName) => + { + switch (typeFullName) + { + case "MygisPoint": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisPoint))); + case "MygisLineString": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisLineString))); + case "MygisPolygon": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisPolygon))); + case "MygisMultiPoint": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisMultiPoint))); + case "MygisMultiLineString": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisMultiLineString))); + case "MygisMultiPolygon": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodMygisGeometryParse, Expression.Convert(valueExp, typeof(string))), typeof(MygisMultiPolygon))); + } + return null; + }); + } - public ISelect Select() where T1 : class => new MySqlSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public ISelect Select(object dywhere) where T1 : class => new MySqlSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IInsert Insert() where T1 : class => new MySqlInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); - public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); - public IUpdate Update() where T1 : class => new MySqlUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IUpdate Update(object dywhere) where T1 : class => new MySqlUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IDelete Delete() where T1 : class => new MySqlDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IDelete Delete(object dywhere) where T1 : class => new MySqlDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public ISelect Select() where T1 : class => new MySqlSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public ISelect Select(object dywhere) where T1 : class => new MySqlSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IInsert Insert() where T1 : class => new MySqlInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); + public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); + public IUpdate Update() where T1 : class => new MySqlUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IUpdate Update(object dywhere) where T1 : class => new MySqlUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IDelete Delete() where T1 : class => new MySqlDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IDelete Delete(object dywhere) where T1 : class => new MySqlDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IAdo Ado { get; } - public IAop Aop { get; } - public ICodeFirst CodeFirst { get; } - public IDbFirst DbFirst { get; } - public MySqlProvider(string masterConnectionString, string[] slaveConnectionString) { - this.InternalCommonUtils = new MySqlUtils(this); - this.InternalCommonExpression = new MySqlExpression(this.InternalCommonUtils); + public IAdo Ado { get; } + public IAop Aop { get; } + public ICodeFirst CodeFirst { get; } + public IDbFirst DbFirst { get; } + public MySqlProvider(string masterConnectionString, string[] slaveConnectionString) + { + this.InternalCommonUtils = new MySqlUtils(this); + this.InternalCommonExpression = new MySqlExpression(this.InternalCommonUtils); - this.Ado = new MySqlAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); - this.Aop = new AopProvider(); + this.Ado = new MySqlAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); + this.Aop = new AopProvider(); - this.DbFirst = new MySqlDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - this.CodeFirst = new MySqlCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - } + this.DbFirst = new MySqlDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + this.CodeFirst = new MySqlCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + } - internal CommonUtils InternalCommonUtils { get; } - internal CommonExpression InternalCommonExpression { get; } + internal CommonUtils InternalCommonUtils { get; } + internal CommonExpression InternalCommonExpression { get; } - public void Transaction(Action handler) => Ado.Transaction(handler); + public void Transaction(Action handler) => Ado.Transaction(handler); - public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); + public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); - ~MySqlProvider() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - (this.Ado as AdoProvider)?.Dispose(); - } - } + ~MySqlProvider() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + (this.Ado as AdoProvider)?.Dispose(); + } + } } diff --git a/Providers/FreeSql.Provider.MySql/MySqlUtils.cs b/Providers/FreeSql.Provider.MySql/MySqlUtils.cs index 3b6eb16b..2afaf09e 100644 --- a/Providers/FreeSql.Provider.MySql/MySqlUtils.cs +++ b/Providers/FreeSql.Provider.MySql/MySqlUtils.cs @@ -9,97 +9,119 @@ using System.Linq.Expressions; using System.Reflection; using System.Text; -namespace FreeSql.MySql { +namespace FreeSql.MySql +{ - class MySqlUtils : CommonUtils { - public MySqlUtils(IFreeSql orm) : base(orm) { - } + class MySqlUtils : CommonUtils + { + public MySqlUtils(IFreeSql orm) : base(orm) + { + } - public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) { - if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; - var ret = new MySqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; - var tp = _orm.CodeFirst.GetDbInfo(type)?.type; - if (tp != null) { - if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) { - ret.MySqlDbType = MySqlDbType.Text; - if (value != null) ret.Value = (value as MygisGeometry).AsText(); - } else - ret.MySqlDbType = (MySqlDbType)tp.Value; - } - _params?.Add(ret); - return ret; - } + public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) + { + if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; + var ret = new MySqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; + var tp = _orm.CodeFirst.GetDbInfo(type)?.type; + if (tp != null) + { + if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) + { + ret.MySqlDbType = MySqlDbType.Text; + if (value != null) ret.Value = (value as MygisGeometry).AsText(); + } + else + ret.MySqlDbType = (MySqlDbType)tp.Value; + } + _params?.Add(ret); + return ret; + } - public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => - Utils.GetDbParamtersByObject(sql, obj, "?", (name, type, value) => { - var ret = new MySqlParameter { ParameterName = $"?{name}", Value = value }; - var tp = _orm.CodeFirst.GetDbInfo(type)?.type; - if (tp != null) { - if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) { - ret.MySqlDbType = MySqlDbType.Text; - if (value != null) ret.Value = (value as MygisGeometry).AsText(); - } else - ret.MySqlDbType = (MySqlDbType)tp.Value; - } - return ret; - }); + public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => + Utils.GetDbParamtersByObject(sql, obj, "?", (name, type, value) => + { + var ret = new MySqlParameter { ParameterName = $"?{name}", Value = value }; + var tp = _orm.CodeFirst.GetDbInfo(type)?.type; + if (tp != null) + { + if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) + { + ret.MySqlDbType = MySqlDbType.Text; + if (value != null) ret.Value = (value as MygisGeometry).AsText(); + } + else + ret.MySqlDbType = (MySqlDbType)tp.Value; + } + return ret; + }); - public override string FormatSql(string sql, params object[] args) => sql?.FormatMySql(args); - public override string QuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"`{nametrim.Trim('`').Replace(".", "`.`")}`"; - } - public override string TrimQuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"{nametrim.Trim('`').Replace("`.`", ".").Replace(".`", ".")}"; - } - public override string QuoteParamterName(string name) => $"?{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; - public override string IsNull(string sql, object value) => $"ifnull({sql}, {value})"; - public override string StringConcat(string[] objs, Type[] types) => $"concat({string.Join(", ", objs)})"; - public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; - public override string QuoteWriteParamter(Type type, string paramterName) { - switch (type.FullName) { - case "MygisPoint": - case "MygisLineString": - case "MygisPolygon": - case "MygisMultiPoint": - case "MygisMultiLineString": - case "MygisMultiPolygon": return $"ST_GeomFromText({paramterName})"; - } - return paramterName; - } + public override string FormatSql(string sql, params object[] args) => sql?.FormatMySql(args); + public override string QuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"`{nametrim.Trim('`').Replace(".", "`.`")}`"; + } + public override string TrimQuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"{nametrim.Trim('`').Replace("`.`", ".").Replace(".`", ".")}"; + } + public override string QuoteParamterName(string name) => $"?{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; + public override string IsNull(string sql, object value) => $"ifnull({sql}, {value})"; + public override string StringConcat(string[] objs, Type[] types) => $"concat({string.Join(", ", objs)})"; + public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; + public override string QuoteWriteParamter(Type type, string paramterName) + { + switch (type.FullName) + { + case "MygisPoint": + case "MygisLineString": + case "MygisPolygon": + case "MygisMultiPoint": + case "MygisMultiLineString": + case "MygisMultiPolygon": return $"ST_GeomFromText({paramterName})"; + } + return paramterName; + } - public override string QuoteReadColumn(Type type, string columnName) { - switch (type.FullName) { - case "MygisPoint": - case "MygisLineString": - case "MygisPolygon": - case "MygisMultiPoint": - case "MygisMultiLineString": - case "MygisMultiPolygon": return $"AsText({columnName})"; - } - return columnName; - } + public override string QuoteReadColumn(Type type, string columnName) + { + switch (type.FullName) + { + case "MygisPoint": + case "MygisLineString": + case "MygisPolygon": + case "MygisMultiPoint": + case "MygisMultiLineString": + case "MygisMultiPolygon": return $"AsText({columnName})"; + } + return columnName; + } - public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) { - if (value == null) return "NULL"; - if (type == typeof(byte[])) { - var bytes = value as byte[]; - var sb = new StringBuilder().Append("0x"); - foreach (var vc in bytes) { - if (vc < 10) sb.Append("0"); - sb.Append(vc.ToString("X")); - } - return sb.ToString(); //val = Encoding.UTF8.GetString(val as byte[]); - } else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) { - var ts = (TimeSpan)value; - value = $"{Math.Floor(ts.TotalHours)}:{ts.Minutes}:{ts.Seconds}"; - } - return FormatSql("{0}", value, 1); - } - } + public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) + { + if (value == null) return "NULL"; + if (type == typeof(byte[])) + { + var bytes = value as byte[]; + var sb = new StringBuilder().Append("0x"); + foreach (var vc in bytes) + { + if (vc < 10) sb.Append("0"); + sb.Append(vc.ToString("X")); + } + return sb.ToString(); //val = Encoding.UTF8.GetString(val as byte[]); + } + else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) + { + var ts = (TimeSpan)value; + value = $"{Math.Floor(ts.TotalHours)}:{ts.Minutes}:{ts.Seconds}"; + } + return FormatSql("{0}", value, 1); + } + } } diff --git a/Providers/FreeSql.Provider.MySqlConnector/MySqlConnectorUtils.cs b/Providers/FreeSql.Provider.MySqlConnector/MySqlConnectorUtils.cs index 37a02a57..2624d701 100644 --- a/Providers/FreeSql.Provider.MySqlConnector/MySqlConnectorUtils.cs +++ b/Providers/FreeSql.Provider.MySqlConnector/MySqlConnectorUtils.cs @@ -9,103 +9,127 @@ using System.Linq.Expressions; using System.Reflection; using System.Text; -namespace FreeSql.MySql { +namespace FreeSql.MySql +{ - class MySqlUtils : CommonUtils { - public MySqlUtils(IFreeSql orm) : base(orm) { - } + class MySqlUtils : CommonUtils + { + public MySqlUtils(IFreeSql orm) : base(orm) + { + } - public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) { - if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; - var ret = new MySqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; - var tp = _orm.CodeFirst.GetDbInfo(type)?.type; - if (tp != null) { - if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) { - ret.MySqlDbType = MySqlDbType.Text; - if (value != null) ret.Value = (value as MygisGeometry).AsText(); - } else { - ret.MySqlDbType = (MySqlDbType)tp.Value; - if (ret.MySqlDbType == MySqlDbType.Enum && value != null) - ret.Value = (long)Convert.ChangeType(value, typeof(long)) + 1; - } - } - _params?.Add(ret); - return ret; - } + public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) + { + if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; + var ret = new MySqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; + var tp = _orm.CodeFirst.GetDbInfo(type)?.type; + if (tp != null) + { + if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) + { + ret.MySqlDbType = MySqlDbType.Text; + if (value != null) ret.Value = (value as MygisGeometry).AsText(); + } + else + { + ret.MySqlDbType = (MySqlDbType)tp.Value; + if (ret.MySqlDbType == MySqlDbType.Enum && value != null) + ret.Value = (long)Convert.ChangeType(value, typeof(long)) + 1; + } + } + _params?.Add(ret); + return ret; + } - public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => - Utils.GetDbParamtersByObject(sql, obj, "@", (name, type, value) => { - var ret = new MySqlParameter { ParameterName = $"@{name}", Value = value }; - var tp = _orm.CodeFirst.GetDbInfo(type)?.type; - if (tp != null) { - if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) { - ret.MySqlDbType = MySqlDbType.Text; - if (value != null) ret.Value = (value as MygisGeometry).AsText(); - } else { - ret.MySqlDbType = (MySqlDbType)tp.Value; - if (ret.MySqlDbType == MySqlDbType.Enum && value != null) - ret.Value = (long)Convert.ChangeType(value, typeof(long)) + 1; - } - } - return ret; - }); + public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => + Utils.GetDbParamtersByObject(sql, obj, "@", (name, type, value) => + { + var ret = new MySqlParameter { ParameterName = $"@{name}", Value = value }; + var tp = _orm.CodeFirst.GetDbInfo(type)?.type; + if (tp != null) + { + if ((MySqlDbType)tp.Value == MySqlDbType.Geometry) + { + ret.MySqlDbType = MySqlDbType.Text; + if (value != null) ret.Value = (value as MygisGeometry).AsText(); + } + else + { + ret.MySqlDbType = (MySqlDbType)tp.Value; + if (ret.MySqlDbType == MySqlDbType.Enum && value != null) + ret.Value = (long)Convert.ChangeType(value, typeof(long)) + 1; + } + } + return ret; + }); - public override string FormatSql(string sql, params object[] args) => sql?.FormatMySql(args); - public override string QuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"`{nametrim.Trim('`').Replace(".", "`.`")}`"; - } - public override string TrimQuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"{nametrim.Trim('`').Replace("`.`", ".").Replace(".`", ".")}"; - } - public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; - public override string IsNull(string sql, object value) => $"ifnull({sql}, {value})"; - public override string StringConcat(string[] objs, Type[] types) => $"concat({string.Join(", ", objs)})"; - public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; - public override string QuoteWriteParamter(Type type, string paramterName) { - switch (type.FullName) { - case "MygisPoint": - case "MygisLineString": - case "MygisPolygon": - case "MygisMultiPoint": - case "MygisMultiLineString": - case "MygisMultiPolygon": return $"ST_GeomFromText({paramterName})"; - } - return paramterName; - } + public override string FormatSql(string sql, params object[] args) => sql?.FormatMySql(args); + public override string QuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"`{nametrim.Trim('`').Replace(".", "`.`")}`"; + } + public override string TrimQuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"{nametrim.Trim('`').Replace("`.`", ".").Replace(".`", ".")}"; + } + public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; + public override string IsNull(string sql, object value) => $"ifnull({sql}, {value})"; + public override string StringConcat(string[] objs, Type[] types) => $"concat({string.Join(", ", objs)})"; + public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; + public override string QuoteWriteParamter(Type type, string paramterName) + { + switch (type.FullName) + { + case "MygisPoint": + case "MygisLineString": + case "MygisPolygon": + case "MygisMultiPoint": + case "MygisMultiLineString": + case "MygisMultiPolygon": return $"ST_GeomFromText({paramterName})"; + } + return paramterName; + } - public override string QuoteReadColumn(Type type, string columnName) { - switch (type.FullName) { - case "MygisPoint": - case "MygisLineString": - case "MygisPolygon": - case "MygisMultiPoint": - case "MygisMultiLineString": - case "MygisMultiPolygon": return $"AsText({columnName})"; - } - return columnName; - } + public override string QuoteReadColumn(Type type, string columnName) + { + switch (type.FullName) + { + case "MygisPoint": + case "MygisLineString": + case "MygisPolygon": + case "MygisMultiPoint": + case "MygisMultiLineString": + case "MygisMultiPolygon": return $"AsText({columnName})"; + } + return columnName; + } - public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) { - if (value == null) return "NULL"; - if (type == typeof(byte[])) { - var bytes = value as byte[]; - var sb = new StringBuilder().Append("0x"); - foreach (var vc in bytes) { - if (vc < 10) sb.Append("0"); - sb.Append(vc.ToString("X")); - } - return sb.ToString(); //val = Encoding.UTF8.GetString(val as byte[]); - } else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) { - var ts = (TimeSpan)value; - value = $"{Math.Floor(ts.TotalHours)}:{ts.Minutes}:{ts.Seconds}"; - } - return FormatSql("{0}", value, 1); - } - } + public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) + { + if (value == null) return "NULL"; + if (type == typeof(byte[])) + { + var bytes = value as byte[]; + var sb = new StringBuilder().Append("0x"); + foreach (var vc in bytes) + { + if (vc < 10) sb.Append("0"); + sb.Append(vc.ToString("X")); + } + return sb.ToString(); //val = Encoding.UTF8.GetString(val as byte[]); + } + else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) + { + var ts = (TimeSpan)value; + value = $"{Math.Floor(ts.TotalHours)}:{ts.Minutes}:{ts.Seconds}"; + } + return FormatSql("{0}", value, 1); + } + } } diff --git a/Providers/FreeSql.Provider.Oracle/Curd/OracleDelete.cs b/Providers/FreeSql.Provider.Oracle/Curd/OracleDelete.cs index 7525b00e..3f6be169 100644 --- a/Providers/FreeSql.Provider.Oracle/Curd/OracleDelete.cs +++ b/Providers/FreeSql.Provider.Oracle/Curd/OracleDelete.cs @@ -5,18 +5,23 @@ using System.Data; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Oracle.Curd { +namespace FreeSql.Oracle.Curd +{ - class OracleDelete : Internal.CommonProvider.DeleteProvider where T1 : class { - public OracleDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + class OracleDelete : Internal.CommonProvider.DeleteProvider where T1 : class + { + public OracleDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override List ExecuteDeleted() { - throw new NotImplementedException(); - } - public override Task> ExecuteDeletedAsync() { - throw new NotImplementedException(); - } - } + public override List ExecuteDeleted() + { + throw new NotImplementedException(); + } + public override Task> ExecuteDeletedAsync() + { + throw new NotImplementedException(); + } + } } diff --git a/Providers/FreeSql.Provider.Oracle/Curd/OracleInsert.cs b/Providers/FreeSql.Provider.Oracle/Curd/OracleInsert.cs index a8b1e480..8daaf144 100644 --- a/Providers/FreeSql.Provider.Oracle/Curd/OracleInsert.cs +++ b/Providers/FreeSql.Provider.Oracle/Curd/OracleInsert.cs @@ -9,177 +9,214 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Oracle.Curd { +namespace FreeSql.Oracle.Curd +{ - class OracleInsert : Internal.CommonProvider.InsertProvider where T1 : class { - public OracleInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) - : base(orm, commonUtils, commonExpression) { - } + class OracleInsert : Internal.CommonProvider.InsertProvider where T1 : class + { + public OracleInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + : base(orm, commonUtils, commonExpression) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 999); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 999); - public override long ExecuteIdentity() => base.SplitExecuteIdentity(500, 999); - public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(500, 999); - public override List ExecuteInserted() => base.SplitExecuteInserted(500, 999); - public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(500, 999); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 999); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 999); + public override long ExecuteIdentity() => base.SplitExecuteIdentity(500, 999); + public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(500, 999); + public override List ExecuteInserted() => base.SplitExecuteInserted(500, 999); + public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(500, 999); - public override string ToSql() { - if (_source == null || _source.Any() == false) return null; - var sb = new StringBuilder(); - sb.Append("INSERT "); - if (_source.Count > 1) sb.Append("ALL"); + public override string ToSql() + { + if (_source == null || _source.Any() == false) return null; + var sb = new StringBuilder(); + sb.Append("INSERT "); + if (_source.Count > 1) sb.Append("ALL"); - _identCol = null; - var sbtb = new StringBuilder(); - sbtb.Append("INTO "); - sbtb.Append(_commonUtils.QuoteSqlName(_tableRule?.Invoke(_table.DbName) ?? _table.DbName)).Append("("); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (col.Attribute.IsIdentity == true) { - _identCol = col; - continue; - } - if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) { - if (colidx > 0) sbtb.Append(", "); - sbtb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)); - ++colidx; - } - } - sbtb.Append(") "); + _identCol = null; + var sbtb = new StringBuilder(); + sbtb.Append("INTO "); + sbtb.Append(_commonUtils.QuoteSqlName(_tableRule?.Invoke(_table.DbName) ?? _table.DbName)).Append("("); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (col.Attribute.IsIdentity == true) + { + _identCol = col; + continue; + } + if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) + { + if (colidx > 0) sbtb.Append(", "); + sbtb.Append(_commonUtils.QuoteSqlName(col.Attribute.Name)); + ++colidx; + } + } + sbtb.Append(") "); - _params = _noneParameter ? new DbParameter[0] : new DbParameter[colidx * _source.Count]; - var specialParams = new List(); - var didx = 0; - foreach (var d in _source) { - if (_source.Count > 1) sb.Append("\r\n"); - sb.Append(sbtb); - sb.Append("VALUES"); - sb.Append("("); - var colidx2 = 0; - foreach (var col in _table.Columns.Values) { - if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) { - if (colidx2 > 0) sb.Append(", "); - object val = col.GetMapValue(d); - if (col.Attribute.IsPrimary && col.Attribute.MapType.NullableTypeOrThis() == typeof(Guid) && (val == null || (Guid)val == Guid.Empty)) - col.SetMapValue(d, val = FreeUtil.NewMongodbId()); - if (_noneParameter) - sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); - else { - sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); - _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col.Attribute.MapType, val); - } - ++colidx2; - } - } - sb.Append(")"); - ++didx; - } - if (_source.Count > 1) sb.Append("\r\n SELECT 1 FROM DUAL"); - return sb.ToString(); - } + _params = _noneParameter ? new DbParameter[0] : new DbParameter[colidx * _source.Count]; + var specialParams = new List(); + var didx = 0; + foreach (var d in _source) + { + if (_source.Count > 1) sb.Append("\r\n"); + sb.Append(sbtb); + sb.Append("VALUES"); + sb.Append("("); + var colidx2 = 0; + foreach (var col in _table.Columns.Values) + { + if (col.Attribute.IsIdentity == false && _ignore.ContainsKey(col.Attribute.Name) == false) + { + if (colidx2 > 0) sb.Append(", "); + object val = col.GetMapValue(d); + if (col.Attribute.IsPrimary && col.Attribute.MapType.NullableTypeOrThis() == typeof(Guid) && (val == null || (Guid)val == Guid.Empty)) + col.SetMapValue(d, val = FreeUtil.NewMongodbId()); + if (_noneParameter) + sb.Append(_commonUtils.GetNoneParamaterSqlValue(specialParams, col.Attribute.MapType, val)); + else + { + sb.Append(_commonUtils.QuoteWriteParamter(col.Attribute.MapType, _commonUtils.QuoteParamterName($"{col.CsName}_{didx}"))); + _params[didx * colidx + colidx2] = _commonUtils.AppendParamter(null, $"{col.CsName}_{didx}", col.Attribute.MapType, val); + } + ++colidx2; + } + } + sb.Append(")"); + ++didx; + } + if (_source.Count > 1) sb.Append("\r\n SELECT 1 FROM DUAL"); + return sb.ToString(); + } - ColumnInfo _identCol; - protected override long RawExecuteIdentity() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + ColumnInfo _identCol; + protected override long RawExecuteIdentity() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - long ret = 0; - Exception exception = null; - Aop.CurdBeforeEventArgs before = null; + long ret = 0; + Exception exception = null; + Aop.CurdBeforeEventArgs before = null; - if (_identCol == null || _source.Count > 1) { - before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - try { - ret = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return 0; - } - var identColName = _commonUtils.QuoteSqlName(_identCol.Attribute.Name); - var identParam = _commonUtils.AppendParamter(null, $"{_identCol.CsName}99", _identCol.Attribute.MapType, 0) as OracleParameter; - identParam.Direction = ParameterDirection.Output; - sql = $"{sql} RETURNING {identColName} INTO {identParam.ParameterName}"; - var dbParms = _params.Concat(new[] { identParam }).ToArray(); - before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - try { - _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, dbParms); - long.TryParse(string.Concat(identParam.Value), out ret); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task RawExecuteIdentityAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + if (_identCol == null || _source.Count > 1) + { + before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + try + { + ret = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return 0; + } + var identColName = _commonUtils.QuoteSqlName(_identCol.Attribute.Name); + var identParam = _commonUtils.AppendParamter(null, $"{_identCol.CsName}99", _identCol.Attribute.MapType, 0) as OracleParameter; + identParam.Direction = ParameterDirection.Output; + sql = $"{sql} RETURNING {identColName} INTO {identParam.ParameterName}"; + var dbParms = _params.Concat(new[] { identParam }).ToArray(); + before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + try + { + _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, dbParms); + long.TryParse(string.Concat(identParam.Value), out ret); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task RawExecuteIdentityAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - long ret = 0; - Exception exception = null; - Aop.CurdBeforeEventArgs before = null; + long ret = 0; + Exception exception = null; + Aop.CurdBeforeEventArgs before = null; - if (_identCol == null || _source.Count > 1) { - before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - try { - ret = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return 0; - } - var identColName = _commonUtils.QuoteSqlName(_identCol.Attribute.Name); - var identParam = _commonUtils.AppendParamter(null, $"{_identCol.CsName}99", _identCol.Attribute.MapType, 0) as OracleParameter; - identParam.Direction = ParameterDirection.Output; - sql = $"{sql} RETURNING {identColName} INTO {identParam.ParameterName}"; - var dbParms = _params.Concat(new[] { identParam }).ToArray(); - before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - try { - await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - long.TryParse(string.Concat(identParam.Value), out ret); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } + if (_identCol == null || _source.Count > 1) + { + before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + try + { + ret = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return 0; + } + var identColName = _commonUtils.QuoteSqlName(_identCol.Attribute.Name); + var identParam = _commonUtils.AppendParamter(null, $"{_identCol.CsName}99", _identCol.Attribute.MapType, 0) as OracleParameter; + identParam.Direction = ParameterDirection.Output; + sql = $"{sql} RETURNING {identColName} INTO {identParam.ParameterName}"; + var dbParms = _params.Concat(new[] { identParam }).ToArray(); + before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + try + { + await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + long.TryParse(string.Concat(identParam.Value), out ret); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } - protected override List RawExecuteInserted() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + protected override List RawExecuteInserted() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - this.RawExecuteAffrows(); - return _source; - } - async protected override Task> RawExecuteInsertedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + this.RawExecuteAffrows(); + return _source; + } + async protected override Task> RawExecuteInsertedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - await this.RawExecuteAffrowsAsync(); - return _source; - } - } + await this.RawExecuteAffrowsAsync(); + return _source; + } + } } diff --git a/Providers/FreeSql.Provider.Oracle/Curd/OracleSelect.cs b/Providers/FreeSql.Provider.Oracle/Curd/OracleSelect.cs index 24dcecda..d11da9a0 100644 --- a/Providers/FreeSql.Provider.Oracle/Curd/OracleSelect.cs +++ b/Providers/FreeSql.Provider.Oracle/Curd/OracleSelect.cs @@ -6,135 +6,161 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.Oracle.Curd { +namespace FreeSql.Oracle.Curd +{ - class OracleSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class { + class OracleSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class + { - internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) { - if (_orm.CodeFirst.IsAutoSyncStructure) - _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); + internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) + { + if (_orm.CodeFirst.IsAutoSyncStructure) + _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); - var sb = new StringBuilder(); - var sbnav = new StringBuilder(); - sb.Append(_select); - if (_distinct) sb.Append("DISTINCT "); - sb.Append(field); - if (string.IsNullOrEmpty(_orderby) && _skip > 0) sb.Append(", ROWNUM AS \"__rownum__\""); - sb.Append(" \r\nFROM "); - var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); - var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); - for (var a = 0; a < tbsfrom.Length; a++) { - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); - if (tbsjoin.Length > 0) { - //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 - for (var b = 1; b < tbsfrom.Length; b++) { - sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); - if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); - else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); - } - break; - } else { - if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); - if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); - } - if (a < tbsfrom.Length - 1) sb.Append(", "); - } - foreach (var tb in tbsjoin) { - if (tb.Type == SelectTableInfoType.Parent) continue; - switch (tb.Type) { - case SelectTableInfoType.LeftJoin: - sb.Append(" \r\nLEFT JOIN "); - break; - case SelectTableInfoType.InnerJoin: - sb.Append(" \r\nINNER JOIN "); - break; - case SelectTableInfoType.RightJoin: - sb.Append(" \r\nRIGHT JOIN "); - break; - } - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); - if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); - } - if (_join.Length > 0) sb.Append(_join); + var sb = new StringBuilder(); + var sbnav = new StringBuilder(); + sb.Append(_select); + if (_distinct) sb.Append("DISTINCT "); + sb.Append(field); + if (string.IsNullOrEmpty(_orderby) && _skip > 0) sb.Append(", ROWNUM AS \"__rownum__\""); + sb.Append(" \r\nFROM "); + var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); + var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); + for (var a = 0; a < tbsfrom.Length; a++) + { + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); + if (tbsjoin.Length > 0) + { + //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 + for (var b = 1; b < tbsfrom.Length; b++) + { + sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); + if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); + else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); + } + break; + } + else + { + if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); + if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); + } + if (a < tbsfrom.Length - 1) sb.Append(", "); + } + foreach (var tb in tbsjoin) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + switch (tb.Type) + { + case SelectTableInfoType.LeftJoin: + sb.Append(" \r\nLEFT JOIN "); + break; + case SelectTableInfoType.InnerJoin: + sb.Append(" \r\nINNER JOIN "); + break; + case SelectTableInfoType.RightJoin: + sb.Append(" \r\nRIGHT JOIN "); + break; + } + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); + if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); + } + if (_join.Length > 0) sb.Append(_join); - sbnav.Append(_where); - foreach (var tb in _tables) { - if (tb.Type == SelectTableInfoType.Parent) continue; - if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) - sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); - } - if (string.IsNullOrEmpty(_orderby) && (_skip > 0 || _limit > 0)) { - sbnav.Append(" AND ROWNUM < ").Append(_skip + _limit + 1); - } - if (sbnav.Length > 0) { - sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); - } - if (string.IsNullOrEmpty(_groupby) == false) { - sb.Append(_groupby); - if (string.IsNullOrEmpty(_having) == false) - sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); - } - sb.Append(_orderby); + sbnav.Append(_where); + foreach (var tb in _tables) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) + sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); + } + if (string.IsNullOrEmpty(_orderby) && (_skip > 0 || _limit > 0)) + { + sbnav.Append(" AND ROWNUM < ").Append(_skip + _limit + 1); + } + if (sbnav.Length > 0) + { + sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); + } + if (string.IsNullOrEmpty(_groupby) == false) + { + sb.Append(_groupby); + if (string.IsNullOrEmpty(_having) == false) + sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); + } + sb.Append(_orderby); - if (string.IsNullOrEmpty(_orderby)) { - if (_skip > 0) - sb.Insert(0, "SELECT t.* FROM (").Append(") t WHERE t.\"__rownum__\" > ").Append(_skip); - } else { - if (_skip > 0 && _limit > 0) sb.Insert(0, "SELECT t.* FROM (SELECT rt.*, ROWNUM AS \"__rownum__\" FROM (").Append(") rt WHERE ROWNUM < ").Append(_skip + _limit + 1).Append(") t WHERE t.\"__rownum__\" > ").Append(_skip); - else if (_skip > 0) sb.Insert(0, "SELECT t.* FROM (").Append(") t WHERE ROWNUM > ").Append(_skip); - else if (_limit > 0) sb.Insert(0, "SELECT t.* FROM (").Append(") t WHERE ROWNUM < ").Append(_limit + 1); - } + if (string.IsNullOrEmpty(_orderby)) + { + if (_skip > 0) + sb.Insert(0, "SELECT t.* FROM (").Append(") t WHERE t.\"__rownum__\" > ").Append(_skip); + } + else + { + if (_skip > 0 && _limit > 0) sb.Insert(0, "SELECT t.* FROM (SELECT rt.*, ROWNUM AS \"__rownum__\" FROM (").Append(") rt WHERE ROWNUM < ").Append(_skip + _limit + 1).Append(") t WHERE t.\"__rownum__\" > ").Append(_skip); + else if (_skip > 0) sb.Insert(0, "SELECT t.* FROM (").Append(") t WHERE ROWNUM > ").Append(_skip); + else if (_limit > 0) sb.Insert(0, "SELECT t.* FROM (").Append(") t WHERE ROWNUM < ").Append(_limit + 1); + } - sbnav.Clear(); - return sb.ToString(); - } + sbnav.Clear(); + return sb.ToString(); + } - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class OracleSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class { - public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new OracleSelect(_orm, _commonUtils, _commonExpression, null); OracleSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class OracleSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class + { + public OracleSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => OracleSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } } diff --git a/Providers/FreeSql.Provider.Oracle/Curd/OracleUpdate.cs b/Providers/FreeSql.Provider.Oracle/Curd/OracleUpdate.cs index 0347b8ca..7338509f 100644 --- a/Providers/FreeSql.Provider.Oracle/Curd/OracleUpdate.cs +++ b/Providers/FreeSql.Provider.Oracle/Curd/OracleUpdate.cs @@ -7,55 +7,66 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Oracle.Curd { +namespace FreeSql.Oracle.Curd +{ - class OracleUpdate : Internal.CommonProvider.UpdateProvider where T1 : class { + class OracleUpdate : Internal.CommonProvider.UpdateProvider where T1 : class + { - public OracleUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + public OracleUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(200, 999); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(200, 999); - public override List ExecuteUpdated() => base.SplitExecuteUpdated(200, 999); - public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(200, 999); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(200, 999); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(200, 999); + public override List ExecuteUpdated() => base.SplitExecuteUpdated(200, 999); + public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(200, 999); - protected override List RawExecuteUpdated() { - throw new NotImplementedException(); - } - protected override Task> RawExecuteUpdatedAsync() { - throw new NotImplementedException(); - } + protected override List RawExecuteUpdated() + { + throw new NotImplementedException(); + } + protected override Task> RawExecuteUpdatedAsync() + { + throw new NotImplementedException(); + } - protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) { - if (_table.Primarys.Length == 1) { - caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); - return; - } - caseWhen.Append("("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) caseWhen.Append(" || "); - caseWhen.Append(_commonUtils.QuoteReadColumn(pk.Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))); - ++pkidx; - } - caseWhen.Append(")"); - } + protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) + { + if (_table.Primarys.Length == 1) + { + caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); + return; + } + caseWhen.Append("("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) caseWhen.Append(" || "); + caseWhen.Append(_commonUtils.QuoteReadColumn(pk.Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))); + ++pkidx; + } + caseWhen.Append(")"); + } - protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) { - if (_table.Primarys.Length == 1) { - sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); - return; - } - sb.Append("("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) sb.Append(" || "); - sb.Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))); - ++pkidx; - } - sb.Append(")"); - } - } + protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) + { + if (_table.Primarys.Length == 1) + { + sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); + return; + } + sb.Append("("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) sb.Append(" || "); + sb.Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))); + ++pkidx; + } + sb.Append(")"); + } + } } diff --git a/Providers/FreeSql.Provider.Oracle/OracleAdo/OracleAdo.cs b/Providers/FreeSql.Provider.Oracle/OracleAdo/OracleAdo.cs index 249be02a..db16fada 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleAdo/OracleAdo.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleAdo/OracleAdo.cs @@ -7,55 +7,64 @@ using System.Data.Common; using System.Text; using System.Threading; -namespace FreeSql.Oracle { - class OracleAdo : FreeSql.Internal.CommonProvider.AdoProvider { - public OracleAdo() : base(DataType.Oracle) { } - public OracleAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.Oracle) { - base._util = util; - if (!string.IsNullOrEmpty(masterConnectionString)) - MasterPool = new OracleConnectionPool("主库", masterConnectionString, null, null); - if (slaveConnectionStrings != null) { - foreach (var slaveConnectionString in slaveConnectionStrings) { - var slavePool = new OracleConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); - SlavePools.Add(slavePool); - } - } - } - static DateTime dt1970 = new DateTime(1970, 1, 1); - public override object AddslashesProcessParam(object param, Type mapType) { - if (param == null) return "NULL"; - if (mapType != null && mapType != param.GetType()) - param = Utils.GetDataReaderValue(mapType, param); - if (param is bool || param is bool?) - return (bool)param ? 1 : 0; - else if (param is string || param is char) - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - else if (param is Enum) - return ((Enum)param).ToInt64(); - else if (decimal.TryParse(string.Concat(param), out var trydec)) - return param; - else if (param is DateTime || param is DateTime?) - return string.Concat("to_timestamp('", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.ffffff"), "','YYYY-MM-DD HH24:MI:SS.FF6')"); - else if (param is TimeSpan || param is TimeSpan?) - return $"numtodsinterval({((TimeSpan)param).Ticks * 1.0 / 10000000},'second')"; - else if (param is IEnumerable) { - var sb = new StringBuilder(); - var ie = param as IEnumerable; - foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); - return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); - } - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - //if (param is string) return string.Concat('N', nparms[a]); - } +namespace FreeSql.Oracle +{ + class OracleAdo : FreeSql.Internal.CommonProvider.AdoProvider + { + public OracleAdo() : base(DataType.Oracle) { } + public OracleAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.Oracle) + { + base._util = util; + if (!string.IsNullOrEmpty(masterConnectionString)) + MasterPool = new OracleConnectionPool("主库", masterConnectionString, null, null); + if (slaveConnectionStrings != null) + { + foreach (var slaveConnectionString in slaveConnectionStrings) + { + var slavePool = new OracleConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); + SlavePools.Add(slavePool); + } + } + } + static DateTime dt1970 = new DateTime(1970, 1, 1); + public override object AddslashesProcessParam(object param, Type mapType) + { + if (param == null) return "NULL"; + if (mapType != null && mapType != param.GetType()) + param = Utils.GetDataReaderValue(mapType, param); + if (param is bool || param is bool?) + return (bool)param ? 1 : 0; + else if (param is string || param is char) + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + else if (param is Enum) + return ((Enum)param).ToInt64(); + else if (decimal.TryParse(string.Concat(param), out var trydec)) + return param; + else if (param is DateTime || param is DateTime?) + return string.Concat("to_timestamp('", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.ffffff"), "','YYYY-MM-DD HH24:MI:SS.FF6')"); + else if (param is TimeSpan || param is TimeSpan?) + return $"numtodsinterval({((TimeSpan)param).Ticks * 1.0 / 10000000},'second')"; + else if (param is IEnumerable) + { + var sb = new StringBuilder(); + var ie = param as IEnumerable; + foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); + return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); + } + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + //if (param is string) return string.Concat('N', nparms[a]); + } - protected override DbCommand CreateCommand() { - return new OracleCommand(); - } + protected override DbCommand CreateCommand() + { + return new OracleCommand(); + } - protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) { - (pool as OracleConnectionPool).Return(conn, ex); - } + protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) + { + (pool as OracleConnectionPool).Return(conn, ex); + } - protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); - } + protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); + } } diff --git a/Providers/FreeSql.Provider.Oracle/OracleAdo/OracleConnectionPool.cs b/Providers/FreeSql.Provider.Oracle/OracleAdo/OracleConnectionPool.cs index 61b60d55..18b1502e 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleAdo/OracleConnectionPool.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleAdo/OracleConnectionPool.cs @@ -9,183 +9,226 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; -namespace FreeSql.Oracle { +namespace FreeSql.Oracle +{ - class OracleConnectionPool : ObjectPool { + class OracleConnectionPool : ObjectPool + { - internal Action availableHandler; - internal Action unavailableHandler; - internal string UserId { get; set; } + internal Action availableHandler; + internal Action unavailableHandler; + internal string UserId { get; set; } - public OracleConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) { - var userIdMatch = Regex.Match(connectionString, @"User\s+Id\s*=\s*([^;]+)", RegexOptions.IgnoreCase); - if (userIdMatch.Success == false) throw new Exception(@"从 ConnectionString 中无法匹配 User\s+Id\s+=([^;]+)"); - this.UserId = userIdMatch.Groups[1].Value.Trim().ToUpper(); + public OracleConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) + { + var userIdMatch = Regex.Match(connectionString, @"User\s+Id\s*=\s*([^;]+)", RegexOptions.IgnoreCase); + if (userIdMatch.Success == false) throw new Exception(@"从 ConnectionString 中无法匹配 User\s+Id\s+=([^;]+)"); + this.UserId = userIdMatch.Groups[1].Value.Trim().ToUpper(); - var policy = new OracleConnectionPoolPolicy { - _pool = this, - Name = name - }; - this.Policy = policy; - policy.ConnectionString = connectionString; + var policy = new OracleConnectionPoolPolicy + { + _pool = this, + Name = name + }; + this.Policy = policy; + policy.ConnectionString = connectionString; - this.availableHandler = availableHandler; - this.unavailableHandler = unavailableHandler; - } + this.availableHandler = availableHandler; + this.unavailableHandler = unavailableHandler; + } - public void Return(Object obj, Exception exception, bool isRecreate = false) { - if (exception != null && exception is OracleException) { + public void Return(Object obj, Exception exception, bool isRecreate = false) + { + if (exception != null && exception is OracleException) + { - if (exception is System.IO.IOException) { + if (exception is System.IO.IOException) + { - base.SetUnavailable(exception); + base.SetUnavailable(exception); - } else if (obj.Value.Ping() == false) { + } + else if (obj.Value.Ping() == false) + { - base.SetUnavailable(exception); - } - } - base.Return(obj, isRecreate); - } - } + base.SetUnavailable(exception); + } + } + base.Return(obj, isRecreate); + } + } - class OracleConnectionPoolPolicy : IPolicy { + class OracleConnectionPoolPolicy : IPolicy + { - internal OracleConnectionPool _pool; - public string Name { get; set; } = "Oracle Connection 对象池"; - public int PoolSize { get; set; } = 100; - public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); - public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; - public int AsyncGetCapacity { get; set; } = 10000; - public bool IsThrowGetTimeoutException { get; set; } = true; - public int CheckAvailableInterval { get; set; } = 5; + internal OracleConnectionPool _pool; + public string Name { get; set; } = "Oracle Connection 对象池"; + public int PoolSize { get; set; } = 100; + public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); + public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; + public int AsyncGetCapacity { get; set; } = 10000; + public bool IsThrowGetTimeoutException { get; set; } = true; + public int CheckAvailableInterval { get; set; } = 5; - static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - private string _connectionString; - public string ConnectionString { - get => _connectionString; - set { - _connectionString = value ?? ""; + static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + private string _connectionString; + public string ConnectionString + { + get => _connectionString; + set + { + _connectionString = value ?? ""; - var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)"; - Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100; - var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); - PoolSize = poolsize + connStrIncr; - _connectionString = m.Success ? - Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) : - $"{_connectionString};Max pool size={PoolSize}"; + var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)"; + Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100; + var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); + PoolSize = poolsize + connStrIncr; + _connectionString = m.Success ? + Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) : + $"{_connectionString};Max pool size={PoolSize}"; - pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - var minPoolSize = 0; - pattern = @"Min\s*pool\s*size\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - minPoolSize = int.Parse(m.Groups[1].Value); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + var minPoolSize = 0; + pattern = @"Min\s*pool\s*size\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + minPoolSize = int.Parse(m.Groups[1].Value); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); - } - } + FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); + } + } - public bool OnCheckAvailable(Object obj) { - if (obj.Value.State == ConnectionState.Closed) obj.Value.Open(); - return obj.Value.Ping(true); - } + public bool OnCheckAvailable(Object obj) + { + if (obj.Value.State == ConnectionState.Closed) obj.Value.Open(); + return obj.Value.Ping(true); + } - public DbConnection OnCreate() { - var conn = new OracleConnection(_connectionString); - return conn; - } + public DbConnection OnCreate() + { + var conn = new OracleConnection(_connectionString); + return conn; + } - public void OnDestroy(DbConnection obj) { - if (obj.State != ConnectionState.Closed) obj.Close(); - obj.Dispose(); - } + public void OnDestroy(DbConnection obj) + { + if (obj.State != ConnectionState.Closed) obj.Close(); + obj.Dispose(); + } - public void OnGet(Object obj) { + public void OnGet(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) + { - try { - obj.Value.Open(); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + obj.Value.Open(); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - async public Task OnGetAsync(Object obj) { + async public Task OnGetAsync(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) + { - try { - await obj.Value.OpenAsync(); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + await obj.Value.OpenAsync(); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - public void OnGetTimeout() { + public void OnGetTimeout() + { - } + } - public void OnReturn(Object obj) { + public void OnReturn(Object obj) + { - } + } - public void OnAvailable() { - _pool.availableHandler?.Invoke(); - } + public void OnAvailable() + { + _pool.availableHandler?.Invoke(); + } - public void OnUnavailable() { - _pool.unavailableHandler?.Invoke(); - } - } + public void OnUnavailable() + { + _pool.unavailableHandler?.Invoke(); + } + } - static class DbConnectionExtensions { + static class DbConnectionExtensions + { - static DbCommand PingCommand(DbConnection conn) { - var cmd = conn.CreateCommand(); - cmd.CommandTimeout = 5; - cmd.CommandText = "select 1 from dual"; - return cmd; - } - public static bool Ping(this DbConnection that, bool isThrow = false) { - try { - PingCommand(that).ExecuteNonQuery(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - async public static Task PingAsync(this DbConnection that, bool isThrow = false) { - try { - await PingCommand(that).ExecuteNonQueryAsync(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - } + static DbCommand PingCommand(DbConnection conn) + { + var cmd = conn.CreateCommand(); + cmd.CommandTimeout = 5; + cmd.CommandText = "select 1 from dual"; + return cmd; + } + public static bool Ping(this DbConnection that, bool isThrow = false) + { + try + { + PingCommand(that).ExecuteNonQuery(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + async public static Task PingAsync(this DbConnection that, bool isThrow = false) + { + try + { + await PingCommand(that).ExecuteNonQueryAsync(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + } } diff --git a/Providers/FreeSql.Provider.Oracle/OracleCodeFirst.cs b/Providers/FreeSql.Provider.Oracle/OracleCodeFirst.cs index 7d59e1c1..ec8f0dc9 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleCodeFirst.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleCodeFirst.cs @@ -11,126 +11,143 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; -namespace FreeSql.Oracle { +namespace FreeSql.Oracle +{ - class OracleCodeFirst : Internal.CommonProvider.CodeFirstProvider { + class OracleCodeFirst : Internal.CommonProvider.CodeFirstProvider + { - public OracleCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } + public OracleCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } - static object _dicCsToDbLock = new object(); - static Dictionary _dicCsToDb = new Dictionary() { - { typeof(bool).FullName, (OracleDbType.Boolean, "number","number(1) NOT NULL", null, false, false) },{ typeof(bool?).FullName, (OracleDbType.Boolean, "number","number(1) NULL", null, true, null) }, + static object _dicCsToDbLock = new object(); + static Dictionary _dicCsToDb = new Dictionary() { + { typeof(bool).FullName, (OracleDbType.Boolean, "number","number(1) NOT NULL", null, false, false) },{ typeof(bool?).FullName, (OracleDbType.Boolean, "number","number(1) NULL", null, true, null) }, - { typeof(sbyte).FullName, (OracleDbType.Decimal, "number", "number(4) NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (OracleDbType.Decimal, "number", "number(4) NULL", false, true, null) }, - { typeof(short).FullName, (OracleDbType.Int16, "number","number(6) NOT NULL", false, false, 0) },{ typeof(short?).FullName, (OracleDbType.Int16, "number", "number(6) NULL", false, true, null) }, - { typeof(int).FullName, (OracleDbType.Int32, "number", "number(11) NOT NULL", false, false, 0) },{ typeof(int?).FullName, (OracleDbType.Int32, "number", "number(11) NULL", false, true, null) }, - { typeof(long).FullName, (OracleDbType.Int64, "number","number(21) NOT NULL", false, false, 0) },{ typeof(long?).FullName, (OracleDbType.Int64, "number","number(21) NULL", false, true, null) }, + { typeof(sbyte).FullName, (OracleDbType.Decimal, "number", "number(4) NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (OracleDbType.Decimal, "number", "number(4) NULL", false, true, null) }, + { typeof(short).FullName, (OracleDbType.Int16, "number","number(6) NOT NULL", false, false, 0) },{ typeof(short?).FullName, (OracleDbType.Int16, "number", "number(6) NULL", false, true, null) }, + { typeof(int).FullName, (OracleDbType.Int32, "number", "number(11) NOT NULL", false, false, 0) },{ typeof(int?).FullName, (OracleDbType.Int32, "number", "number(11) NULL", false, true, null) }, + { typeof(long).FullName, (OracleDbType.Int64, "number","number(21) NOT NULL", false, false, 0) },{ typeof(long?).FullName, (OracleDbType.Int64, "number","number(21) NULL", false, true, null) }, - { typeof(byte).FullName, (OracleDbType.Byte, "number","number(3) NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (OracleDbType.Byte, "number","number(3) NULL", true, true, null) }, - { typeof(ushort).FullName, (OracleDbType.Decimal, "number","number(5) NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (OracleDbType.Decimal, "number", "number(5) NULL", true, true, null) }, - { typeof(uint).FullName, (OracleDbType.Decimal, "number", "number(10) NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (OracleDbType.Decimal, "number", "number(10) NULL", true, true, null) }, - { typeof(ulong).FullName, (OracleDbType.Decimal, "number", "number(20) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (OracleDbType.Decimal, "number", "number(20) NULL", true, true, null) }, + { typeof(byte).FullName, (OracleDbType.Byte, "number","number(3) NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (OracleDbType.Byte, "number","number(3) NULL", true, true, null) }, + { typeof(ushort).FullName, (OracleDbType.Decimal, "number","number(5) NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (OracleDbType.Decimal, "number", "number(5) NULL", true, true, null) }, + { typeof(uint).FullName, (OracleDbType.Decimal, "number", "number(10) NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (OracleDbType.Decimal, "number", "number(10) NULL", true, true, null) }, + { typeof(ulong).FullName, (OracleDbType.Decimal, "number", "number(20) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (OracleDbType.Decimal, "number", "number(20) NULL", true, true, null) }, - { typeof(double).FullName, (OracleDbType.Double, "float", "float(126) NOT NULL", false, false, 0) },{ typeof(double?).FullName, (OracleDbType.Double, "float", "float(126) NULL", false, true, null) }, - { typeof(float).FullName, (OracleDbType.Single, "float","float(63) NOT NULL", false, false, 0) },{ typeof(float?).FullName, (OracleDbType.Single, "float","float(63) NULL", false, true, null) }, - { typeof(decimal).FullName, (OracleDbType.Decimal, "number", "number(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (OracleDbType.Decimal, "number", "number(10,2) NULL", false, true, null) }, + { typeof(double).FullName, (OracleDbType.Double, "float", "float(126) NOT NULL", false, false, 0) },{ typeof(double?).FullName, (OracleDbType.Double, "float", "float(126) NULL", false, true, null) }, + { typeof(float).FullName, (OracleDbType.Single, "float","float(63) NOT NULL", false, false, 0) },{ typeof(float?).FullName, (OracleDbType.Single, "float","float(63) NULL", false, true, null) }, + { typeof(decimal).FullName, (OracleDbType.Decimal, "number", "number(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (OracleDbType.Decimal, "number", "number(10,2) NULL", false, true, null) }, - { typeof(TimeSpan).FullName, (OracleDbType.IntervalDS, "interval day to second","interval day(2) to second(6) NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (OracleDbType.IntervalDS, "interval day to second", "interval day(2) to second(6) NULL",false, true, null) }, - { typeof(DateTime).FullName, (OracleDbType.TimeStamp, "timestamp", "timestamp(6) NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (OracleDbType.TimeStamp, "timestamp", "timestamp(6) NULL", false, true, null) }, - { typeof(DateTimeOffset).FullName, (OracleDbType.TimeStampLTZ, "timestamp with local time zone", "timestamp(6) with local time zone NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTimeOffset?).FullName, (OracleDbType.TimeStampLTZ, "timestamp with local time zone", "timestamp(6) with local time zone NULL", false, true, null) }, + { typeof(TimeSpan).FullName, (OracleDbType.IntervalDS, "interval day to second","interval day(2) to second(6) NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (OracleDbType.IntervalDS, "interval day to second", "interval day(2) to second(6) NULL",false, true, null) }, + { typeof(DateTime).FullName, (OracleDbType.TimeStamp, "timestamp", "timestamp(6) NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (OracleDbType.TimeStamp, "timestamp", "timestamp(6) NULL", false, true, null) }, + { typeof(DateTimeOffset).FullName, (OracleDbType.TimeStampLTZ, "timestamp with local time zone", "timestamp(6) with local time zone NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTimeOffset?).FullName, (OracleDbType.TimeStampLTZ, "timestamp with local time zone", "timestamp(6) with local time zone NULL", false, true, null) }, - { typeof(byte[]).FullName, (OracleDbType.Blob, "blob", "blob NULL", false, null, new byte[0]) }, - { typeof(string).FullName, (OracleDbType.NVarchar2, "nvarchar2", "nvarchar2(255) NULL", false, null, "") }, + { typeof(byte[]).FullName, (OracleDbType.Blob, "blob", "blob NULL", false, null, new byte[0]) }, + { typeof(string).FullName, (OracleDbType.NVarchar2, "nvarchar2", "nvarchar2(255) NULL", false, null, "") }, - { typeof(Guid).FullName, (OracleDbType.Char, "char", "char(36 CHAR) NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (OracleDbType.Char, "char", "char(36 CHAR) NULL", false, true, null) }, - }; + { typeof(Guid).FullName, (OracleDbType.Char, "char", "char(36 CHAR) NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (OracleDbType.Char, "char", "char(36 CHAR) NULL", false, true, null) }, + }; - public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) { - if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); - if (type.IsArray) return null; - var enumType = type.IsEnum ? type : null; - if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); - if (enumType != null) { - var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? - (OracleDbType.Int32, "number", $"number(16){(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : - (OracleDbType.Int64, "number", $"number(32){(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); - if (_dicCsToDb.ContainsKey(type.FullName) == false) { - lock (_dicCsToDbLock) { - if (_dicCsToDb.ContainsKey(type.FullName) == false) - _dicCsToDb.Add(type.FullName, newItem); - } - } - return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); - } - return null; - } + public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) + { + if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); + if (type.IsArray) return null; + var enumType = type.IsEnum ? type : null; + if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); + if (enumType != null) + { + var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? + (OracleDbType.Int32, "number", $"number(16){(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : + (OracleDbType.Int64, "number", $"number(32){(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); + if (_dicCsToDb.ContainsKey(type.FullName) == false) + { + lock (_dicCsToDbLock) + { + if (_dicCsToDb.ContainsKey(type.FullName) == false) + _dicCsToDb.Add(type.FullName, newItem); + } + } + return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); + } + return null; + } - public override string GetComparisonDDLStatements(params Type[] entityTypes) { - var userId = (_orm.Ado.MasterPool as OracleConnectionPool).UserId; - var seqcols = new List<(ColumnInfo, string[], bool)>(); //序列 + public override string GetComparisonDDLStatements(params Type[] entityTypes) + { + var userId = (_orm.Ado.MasterPool as OracleConnectionPool).UserId; + var seqcols = new List<(ColumnInfo, string[], bool)>(); //序列 - var sb = new StringBuilder(); - var sbDeclare = new StringBuilder(); - foreach (var entityType in entityTypes) { - if (sb.Length > 0) sb.Append("\r\n"); - var tb = _commonUtils.GetTableByEntity(entityType); - if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); - if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); - var tbname = tb.DbName.Split(new[] { '.' }, 2); - if (tbname?.Length == 1) tbname = new[] { userId, tbname[0] }; + var sb = new StringBuilder(); + var sbDeclare = new StringBuilder(); + foreach (var entityType in entityTypes) + { + if (sb.Length > 0) sb.Append("\r\n"); + var tb = _commonUtils.GetTableByEntity(entityType); + if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); + if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); + var tbname = tb.DbName.Split(new[] { '.' }, 2); + if (tbname?.Length == 1) tbname = new[] { userId, tbname[0] }; - var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名 - if (tboldname?.Length == 1) tboldname = new[] { userId, tboldname[0] }; + var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名 + if (tboldname?.Length == 1) tboldname = new[] { userId, tboldname[0] }; - if (string.Compare(tbname[0], userId) != 0 && _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from sys.dba_users where username={0}", tbname[0])) == null) //创建数据库 - throw new NotImplementedException($"Oracle CodeFirst 不支持代码创建 tablespace 与 schemas {tbname[0]}"); + if (string.Compare(tbname[0], userId) != 0 && _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from sys.dba_users where username={0}", tbname[0])) == null) //创建数据库 + throw new NotImplementedException($"Oracle CodeFirst 不支持代码创建 tablespace 与 schemas {tbname[0]}"); - var sbalter = new StringBuilder(); - var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 - if (_orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from all_tab_comments where owner={0} and table_name={1}", tbname)) == null) { //表不存在 - if (tboldname != null) { - if (_orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from all_tab_comments where owner={0} and table_name={1}", tboldname)) == null) - //模式或表不存在 - tboldname = null; - } - if (tboldname == null) { - //创建表 - sb.Append("execute immediate 'CREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( "); - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(","); - if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, true)); - } - if (tb.Primarys.Any()) { - sb.Append(" \r\n CONSTRAINT ").Append(tbname[0]).Append("_").Append(tbname[1]).Append("_pk1 PRIMARY KEY ("); - foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE ("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1); - sb.Append("\r\n) \r\nLOGGING \r\nNOCOMPRESS \r\nNOCACHE\r\n';\r\n"); - //备注 - foreach (var tbcol in tb.Columns.Values) { - if (string.IsNullOrEmpty(tbcol.Comment) == false) - sb.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment).Replace("'", "''")).Append("';\r\n"); - } - continue; - } - //如果新表,旧表在一个模式下,直接修改表名 - if (string.Compare(tbname[0], tboldname[0], true) == 0) - sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}")).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append("';\r\n"); - else { - //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 - istmpatler = true; - } - } else - tboldname = null; //如果新表已经存在,不走改表名逻辑 + var sbalter = new StringBuilder(); + var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 + if (_orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from all_tab_comments where owner={0} and table_name={1}", tbname)) == null) + { //表不存在 + if (tboldname != null) + { + if (_orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from all_tab_comments where owner={0} and table_name={1}", tboldname)) == null) + //模式或表不存在 + tboldname = null; + } + if (tboldname == null) + { + //创建表 + sb.Append("execute immediate 'CREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( "); + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(","); + if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, true)); + } + if (tb.Primarys.Any()) + { + sb.Append(" \r\n CONSTRAINT ").Append(tbname[0]).Append("_").Append(tbname[1]).Append("_pk1 PRIMARY KEY ("); + foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE ("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1); + sb.Append("\r\n) \r\nLOGGING \r\nNOCOMPRESS \r\nNOCACHE\r\n';\r\n"); + //备注 + foreach (var tbcol in tb.Columns.Values) + { + if (string.IsNullOrEmpty(tbcol.Comment) == false) + sb.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment).Replace("'", "''")).Append("';\r\n"); + } + continue; + } + //如果新表,旧表在一个模式下,直接修改表名 + if (string.Compare(tbname[0], tboldname[0], true) == 0) + sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}")).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append("';\r\n"); + else + { + //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 + istmpatler = true; + } + } + else + tboldname = null; //如果新表已经存在,不走改表名逻辑 - //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 - var sql = _commonUtils.FormatSql($@" + //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 + var sql = _commonUtils.FormatSql($@" select a.column_name, a.data_type, @@ -145,51 +162,58 @@ b.comments from all_tab_columns a left join all_col_comments b on b.owner = a.owner and b.table_name = a.table_name and b.column_name = a.column_name where a.owner={{0}} and a.table_name={{1}}", tboldname ?? tbname); - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => { - var sqlType = GetOracleSqlTypeFullName(a); - return new { - column = string.Concat(a[0]), - sqlType, - is_nullable = string.Concat(a[6]) == "1", - is_identity = string.Concat(a[7]) == "1" && string.Concat(a[8]) == "1", - comment = string.Concat(a[9]) - }; - }, StringComparer.CurrentCultureIgnoreCase); + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => + { + var sqlType = GetOracleSqlTypeFullName(a); + return new + { + column = string.Concat(a[0]), + sqlType, + is_nullable = string.Concat(a[6]) == "1", + is_identity = string.Concat(a[7]) == "1" && string.Concat(a[8]) == "1", + comment = string.Concat(a[9]) + }; + }, StringComparer.CurrentCultureIgnoreCase); - if (istmpatler == false) { - foreach (var tbcol in tb.Columns.Values) { - var dbtypeNoneNotNull = Regex.Replace(tbcol.Attribute.DbType, @"NOT\s+NULL", "NULL"); - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? ""); - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) - istmpatler = true; - //sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY (").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(dbtypeNoneNotNull).Append(")';\r\n"); - if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) { - if (tbcol.Attribute.IsNullable == false) - sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue).Replace("'", "''")).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL';\r\n"); - sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.IsNullable == true ? "" : "NOT").Append(" NULL';\r\n"); - } - if (tbcol.Attribute.IsIdentity != tbstructcol.is_identity) - seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); - if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) - //修改列名 - sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" RENAME COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" TO ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append("';\r\n"); - if (isCommentChanged) - sbalter.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "").Replace("'", "''")).Append("';\r\n"); - continue; - } - //添加列 - sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD (").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(dbtypeNoneNotNull).Append(")';\r\n"); - if (tbcol.Attribute.IsNullable == false) { - sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue).Replace("'", "''")).Append("';\r\n"); - sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" NOT NULL';\r\n"); - } - if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); - if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "").Replace("'", "''")).Append("';\r\n"); - } - var dsuksql = _commonUtils.FormatSql(@" + if (istmpatler == false) + { + foreach (var tbcol in tb.Columns.Values) + { + var dbtypeNoneNotNull = Regex.Replace(tbcol.Attribute.DbType, @"NOT\s+NULL", "NULL"); + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? ""); + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) + istmpatler = true; + //sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY (").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(dbtypeNoneNotNull).Append(")';\r\n"); + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) + { + if (tbcol.Attribute.IsNullable == false) + sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue).Replace("'", "''")).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL';\r\n"); + sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.IsNullable == true ? "" : "NOT").Append(" NULL';\r\n"); + } + if (tbcol.Attribute.IsIdentity != tbstructcol.is_identity) + seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); + if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) + //修改列名 + sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" RENAME COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" TO ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append("';\r\n"); + if (isCommentChanged) + sbalter.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "").Replace("'", "''")).Append("';\r\n"); + continue; + } + //添加列 + sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD (").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(dbtypeNoneNotNull).Append(")';\r\n"); + if (tbcol.Attribute.IsNullable == false) + { + sbalter.Append("execute immediate 'UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue).Replace("'", "''")).Append("';\r\n"); + sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" MODIFY ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" NOT NULL';\r\n"); + } + if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "").Replace("'", "''")).Append("';\r\n"); + } + var dsuksql = _commonUtils.FormatSql(@" select c.column_name, c.constraint_name @@ -202,139 +226,165 @@ and a.owner = c.owner and a.table_name = c.table_name and a.constraint_type in ('U') and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname); - var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) }); - foreach (var uk in tb.Uniques) { - if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; - var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); - if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) { - if (dsukfind1.Any()) sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("';\r\n"); - sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sbalter.Remove(sbalter.Length - 2, 2).Append(")';\r\n"); - } - } - } - if (istmpatler == false) { - sb.Append(sbalter); - continue; - } - var oldpk = _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(@"select constraint_name from user_constraints where owner={0} and table_name={1} and constraint_type='P'", tbname))?.ToString(); - if (string.IsNullOrEmpty(oldpk) == false) - sb.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(oldpk).Append("';\r\n"); + var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) }); + foreach (var uk in tb.Uniques) + { + if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; + var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); + if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) + { + if (dsukfind1.Any()) sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("';\r\n"); + sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sbalter.Remove(sbalter.Length - 2, 2).Append(")';\r\n"); + } + } + } + if (istmpatler == false) + { + sb.Append(sbalter); + continue; + } + var oldpk = _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(@"select constraint_name from user_constraints where owner={0} and table_name={1} and constraint_type='P'", tbname))?.ToString(); + if (string.IsNullOrEmpty(oldpk) == false) + sb.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(oldpk).Append("';\r\n"); - //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 - var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"); - var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.FTmp_{tbname[1]}"); - //创建临时表 - sb.Append("execute immediate 'CREATE TABLE ").Append(tmptablename).Append(" ( "); - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(","); - if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, true)); - } - if (tb.Primarys.Any()) { - sb.Append(" \r\n CONSTRAINT ").Append(tbname[0]).Append("_").Append(tbname[1]).Append("_pk2 PRIMARY KEY ("); - foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE ("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1); - sb.Append("\r\n) LOGGING \r\nNOCOMPRESS \r\nNOCACHE\r\n';\r\n"); - //备注 - foreach (var tbcol in tb.Columns.Values) { - if (string.IsNullOrEmpty(tbcol.Comment) == false) - sb.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.FTmp_{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment).Replace("'", "''")).Append("';\r\n"); - } - sb.Append("execute immediate 'INSERT INTO ").Append(tmptablename).Append(" ("); - foreach (var tbcol in tb.Columns.Values) - sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append(")\r\nSELECT "); - foreach (var tbcol in tb.Columns.Values) { - var insertvalue = "NULL"; - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) { - var dbtypeNoneNotNull = Regex.Replace(tbcol.Attribute.DbType, @"(NOT\s+)?NULL", ""); - insertvalue = $"cast({insertvalue} as {dbtypeNoneNotNull})"; - } - if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"nvl({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; - } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); - sb.Append(insertvalue.Replace("'", "''")).Append(", "); - } - sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append("';\r\n"); - sb.Append("execute immediate 'DROP TABLE ").Append(tablename).Append("';\r\n"); - sb.Append("execute immediate 'ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append("';\r\n"); - } - Dictionary dicDeclare = new Dictionary(); - foreach (var seqcol in seqcols) { - var tbname = seqcol.Item2; - var seqname = Utils.GetCsName($"{tbname[1]}_seq_{seqcol.Item1.Attribute.Name}"); - var tiggerName = seqname + "TI"; - var tbname2 = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}"); - var colname2 = _commonUtils.QuoteSqlName(seqcol.Item1.Attribute.Name); - if (dicDeclare.ContainsKey(seqname) == false) { - sbDeclare.Append("\r\n").Append(seqname).Append("IS NUMBER; \r\n"); - dicDeclare.Add(seqname, true); - } - sb.Append(seqname).Append("IS := 0; \r\n") - .Append(" select count(1) into ").Append(seqname).Append(_commonUtils.FormatSql("IS from user_sequences where sequence_name={0}; \r\n", seqname)) - .Append("if ").Append(seqname).Append("IS > 0 then \r\n") - .Append(" execute immediate 'DROP SEQUENCE ").Append(_commonUtils.QuoteSqlName(seqname)).Append("';\r\n") - .Append("end if; \r\n"); - if (seqcol.Item3) { - var startWith = _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from all_tab_comments where owner={0} and table_name={1}", tbname)) == null ? 1 : - _orm.Ado.ExecuteScalar(CommandType.Text, $" select nvl(max({colname2})+1,1) from {tbname2}"); - sb.Append("execute immediate 'CREATE SEQUENCE ").Append(_commonUtils.QuoteSqlName(seqname)).Append(" start with ").Append(startWith).Append("';\r\n"); - sb.Append("execute immediate 'CREATE OR REPLACE TRIGGER ").Append(_commonUtils.QuoteSqlName(tiggerName)) - .Append(" \r\nbefore insert on ").Append(tbname2) - .Append(" \r\nfor each row \r\nbegin\r\nselect ").Append(_commonUtils.QuoteSqlName(seqname)) - .Append(".nextval into :new.").Append(colname2).Append(" from dual;\r\nend;';\r\n"); - } else { - if (dicDeclare.ContainsKey(tiggerName) == false) { - sbDeclare.Append("\r\n").Append(tiggerName).Append("IS NUMBER; \r\n"); - dicDeclare.Add(tiggerName, true); - } - sb.Append(tiggerName).Append("IS := 0; \r\n") - .Append(" select count(1) into ").Append(tiggerName).Append(_commonUtils.FormatSql("IS from user_triggers where trigger_name={0}; \r\n", tiggerName)) - .Append("if ").Append(tiggerName).Append("IS > 0 then \r\n") - .Append(" execute immediate 'DROP TRIGGER ").Append(_commonUtils.QuoteSqlName(tiggerName)).Append("';\r\n") - .Append("end if; \r\n"); - } - } - if (sbDeclare.Length > 0) sbDeclare.Insert(0, "declare "); - return sb.Length == 0 ? null : sb.Insert(0, "BEGIN \r\n").Insert(0, sbDeclare.ToString()).Append("END;").ToString(); - } + //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 + var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"); + var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.FTmp_{tbname[1]}"); + //创建临时表 + sb.Append("execute immediate 'CREATE TABLE ").Append(tmptablename).Append(" ( "); + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(","); + if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, true)); + } + if (tb.Primarys.Any()) + { + sb.Append(" \r\n CONSTRAINT ").Append(tbname[0]).Append("_").Append(tbname[1]).Append("_pk2 PRIMARY KEY ("); + foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE ("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1); + sb.Append("\r\n) LOGGING \r\nNOCOMPRESS \r\nNOCACHE\r\n';\r\n"); + //备注 + foreach (var tbcol in tb.Columns.Values) + { + if (string.IsNullOrEmpty(tbcol.Comment) == false) + sb.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.FTmp_{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment).Replace("'", "''")).Append("';\r\n"); + } + sb.Append("execute immediate 'INSERT INTO ").Append(tmptablename).Append(" ("); + foreach (var tbcol in tb.Columns.Values) + sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append(")\r\nSELECT "); + foreach (var tbcol in tb.Columns.Values) + { + var insertvalue = "NULL"; + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) + { + var dbtypeNoneNotNull = Regex.Replace(tbcol.Attribute.DbType, @"(NOT\s+)?NULL", ""); + insertvalue = $"cast({insertvalue} as {dbtypeNoneNotNull})"; + } + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) + insertvalue = $"nvl({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + } + else if (tbcol.Attribute.IsNullable == false) + insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + sb.Append(insertvalue.Replace("'", "''")).Append(", "); + } + sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append("';\r\n"); + sb.Append("execute immediate 'DROP TABLE ").Append(tablename).Append("';\r\n"); + sb.Append("execute immediate 'ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append("';\r\n"); + } + Dictionary dicDeclare = new Dictionary(); + foreach (var seqcol in seqcols) + { + var tbname = seqcol.Item2; + var seqname = Utils.GetCsName($"{tbname[1]}_seq_{seqcol.Item1.Attribute.Name}"); + var tiggerName = seqname + "TI"; + var tbname2 = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}"); + var colname2 = _commonUtils.QuoteSqlName(seqcol.Item1.Attribute.Name); + if (dicDeclare.ContainsKey(seqname) == false) + { + sbDeclare.Append("\r\n").Append(seqname).Append("IS NUMBER; \r\n"); + dicDeclare.Add(seqname, true); + } + sb.Append(seqname).Append("IS := 0; \r\n") + .Append(" select count(1) into ").Append(seqname).Append(_commonUtils.FormatSql("IS from user_sequences where sequence_name={0}; \r\n", seqname)) + .Append("if ").Append(seqname).Append("IS > 0 then \r\n") + .Append(" execute immediate 'DROP SEQUENCE ").Append(_commonUtils.QuoteSqlName(seqname)).Append("';\r\n") + .Append("end if; \r\n"); + if (seqcol.Item3) + { + var startWith = _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from all_tab_comments where owner={0} and table_name={1}", tbname)) == null ? 1 : + _orm.Ado.ExecuteScalar(CommandType.Text, $" select nvl(max({colname2})+1,1) from {tbname2}"); + sb.Append("execute immediate 'CREATE SEQUENCE ").Append(_commonUtils.QuoteSqlName(seqname)).Append(" start with ").Append(startWith).Append("';\r\n"); + sb.Append("execute immediate 'CREATE OR REPLACE TRIGGER ").Append(_commonUtils.QuoteSqlName(tiggerName)) + .Append(" \r\nbefore insert on ").Append(tbname2) + .Append(" \r\nfor each row \r\nbegin\r\nselect ").Append(_commonUtils.QuoteSqlName(seqname)) + .Append(".nextval into :new.").Append(colname2).Append(" from dual;\r\nend;';\r\n"); + } + else + { + if (dicDeclare.ContainsKey(tiggerName) == false) + { + sbDeclare.Append("\r\n").Append(tiggerName).Append("IS NUMBER; \r\n"); + dicDeclare.Add(tiggerName, true); + } + sb.Append(tiggerName).Append("IS := 0; \r\n") + .Append(" select count(1) into ").Append(tiggerName).Append(_commonUtils.FormatSql("IS from user_triggers where trigger_name={0}; \r\n", tiggerName)) + .Append("if ").Append(tiggerName).Append("IS > 0 then \r\n") + .Append(" execute immediate 'DROP TRIGGER ").Append(_commonUtils.QuoteSqlName(tiggerName)).Append("';\r\n") + .Append("end if; \r\n"); + } + } + if (sbDeclare.Length > 0) sbDeclare.Insert(0, "declare "); + return sb.Length == 0 ? null : sb.Insert(0, "BEGIN \r\n").Insert(0, sbDeclare.ToString()).Append("END;").ToString(); + } - internal static string GetOracleSqlTypeFullName(object[] row) { - var a = row; - var sqlType = string.Concat(a[1]).ToUpper(); - var data_length = long.Parse(string.Concat(a[2])); - long.TryParse(string.Concat(a[3]), out var data_precision); - long.TryParse(string.Concat(a[4]), out var data_scale); - var char_used = string.Concat(a[5]); - if (Regex.IsMatch(sqlType, @"INTERVAL DAY\(\d+\) TO SECOND\(\d+\)", RegexOptions.IgnoreCase)) { - } else if (Regex.IsMatch(sqlType, @"INTERVAL YEAR\(\d+\) TO MONTH", RegexOptions.IgnoreCase)) { - } else if (sqlType.StartsWith("TIMESTAMP", StringComparison.CurrentCultureIgnoreCase)) { - } else if (sqlType.StartsWith("BLOB")) { - } else if (char_used.ToLower() == "c") - sqlType += sqlType.StartsWith("N") ? $"({data_length / 2})" : $"({data_length / 4} CHAR)"; - else if (char_used.ToLower() == "b") - sqlType += $"({data_length} BYTE)"; - else if (sqlType.ToLower() == "float") - sqlType += $"({data_precision})"; - else if (data_precision > 0 && data_scale > 0) - sqlType += $"({data_precision},{data_scale})"; - else if (data_precision > 0) - sqlType += $"({data_precision})"; - else - sqlType += $"({data_length})"; - return sqlType; - } - } + internal static string GetOracleSqlTypeFullName(object[] row) + { + var a = row; + var sqlType = string.Concat(a[1]).ToUpper(); + var data_length = long.Parse(string.Concat(a[2])); + long.TryParse(string.Concat(a[3]), out var data_precision); + long.TryParse(string.Concat(a[4]), out var data_scale); + var char_used = string.Concat(a[5]); + if (Regex.IsMatch(sqlType, @"INTERVAL DAY\(\d+\) TO SECOND\(\d+\)", RegexOptions.IgnoreCase)) + { + } + else if (Regex.IsMatch(sqlType, @"INTERVAL YEAR\(\d+\) TO MONTH", RegexOptions.IgnoreCase)) + { + } + else if (sqlType.StartsWith("TIMESTAMP", StringComparison.CurrentCultureIgnoreCase)) + { + } + else if (sqlType.StartsWith("BLOB")) + { + } + else if (char_used.ToLower() == "c") + sqlType += sqlType.StartsWith("N") ? $"({data_length / 2})" : $"({data_length / 4} CHAR)"; + else if (char_used.ToLower() == "b") + sqlType += $"({data_length} BYTE)"; + else if (sqlType.ToLower() == "float") + sqlType += $"({data_precision})"; + else if (data_precision > 0 && data_scale > 0) + sqlType += $"({data_precision},{data_scale})"; + else if (data_precision > 0) + sqlType += $"({data_precision})"; + else + sqlType += $"({data_length})"; + return sqlType; + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.Oracle/OracleDbFirst.cs b/Providers/FreeSql.Provider.Oracle/OracleDbFirst.cs index 4d008622..4a3cf4e1 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleDbFirst.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleDbFirst.cs @@ -8,148 +8,158 @@ using System.Data; using System.Linq; using System.Text.RegularExpressions; -namespace FreeSql.Oracle { - class OracleDbFirst : IDbFirst { - IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - public OracleDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - } +namespace FreeSql.Oracle +{ + class OracleDbFirst : IDbFirst + { + IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + public OracleDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + } - public int GetDbType(DbColumnInfo column) => (int)GetSqlDbType(column); - OracleDbType GetSqlDbType(DbColumnInfo column) { - var dbfull = column.DbTypeTextFull.ToLower(); - switch (dbfull) { - case "number(1)": return OracleDbType.Boolean; + public int GetDbType(DbColumnInfo column) => (int)GetSqlDbType(column); + OracleDbType GetSqlDbType(DbColumnInfo column) + { + var dbfull = column.DbTypeTextFull.ToLower(); + switch (dbfull) + { + case "number(1)": return OracleDbType.Boolean; - case "number(4)": return OracleDbType.Decimal; - case "number(6)": return OracleDbType.Int16; - case "number(11)": return OracleDbType.Int32; - case "number(21)": return OracleDbType.Int64; + case "number(4)": return OracleDbType.Decimal; + case "number(6)": return OracleDbType.Int16; + case "number(11)": return OracleDbType.Int32; + case "number(21)": return OracleDbType.Int64; - case "number(3)": return OracleDbType.Byte; - case "number(5)": return OracleDbType.Decimal; - case "number(10)": return OracleDbType.Decimal; - case "number(20)": return OracleDbType.Decimal; + case "number(3)": return OracleDbType.Byte; + case "number(5)": return OracleDbType.Decimal; + case "number(10)": return OracleDbType.Decimal; + case "number(20)": return OracleDbType.Decimal; - case "float(126)": return OracleDbType.Double; - case "float(63)": return OracleDbType.Single; - case "number(10,2)": return OracleDbType.Decimal; + case "float(126)": return OracleDbType.Double; + case "float(63)": return OracleDbType.Single; + case "number(10,2)": return OracleDbType.Decimal; - case "interval day(2) to second(6)": return OracleDbType.IntervalDS; - case "timestamp(6)": return OracleDbType.TimeStamp; - case "timestamp(6) with local time zone": return OracleDbType.TimeStampLTZ; + case "interval day(2) to second(6)": return OracleDbType.IntervalDS; + case "timestamp(6)": return OracleDbType.TimeStamp; + case "timestamp(6) with local time zone": return OracleDbType.TimeStampLTZ; - case "blob": return OracleDbType.Blob; - case "nvarchar2(255)": return OracleDbType.NVarchar2; + case "blob": return OracleDbType.Blob; + case "nvarchar2(255)": return OracleDbType.NVarchar2; - case "char(36 char)": return OracleDbType.Char; - } - switch (column.DbTypeText.ToLower()) { - case "number": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(10,2)"]); - return OracleDbType.Decimal; - case "float": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["float(126)"]); - return OracleDbType.Double; - case "interval day to second": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["interval day(2) to second(6)"]); - return OracleDbType.IntervalDS; - case "date": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["date(7)"]); - return OracleDbType.IntervalDS; - case "timestamp": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["timestamp(6)"]); - return OracleDbType.TimeStamp; - case "timestamp with local time zone": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["timestamp(6) with local time zone"]); - return OracleDbType.TimeStampLTZ; - case "blob": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["blob"]); - return OracleDbType.Blob; - case "nvarchar2": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); - return OracleDbType.NVarchar2; - case "varchar2": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); - return OracleDbType.Varchar2; - case "char": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["char(36 char)"]); - return OracleDbType.Char; - case "clob": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); - return OracleDbType.Clob; - case "nclob": - _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); - return OracleDbType.NClob; - } - throw new NotImplementedException($"未实现 {column.DbTypeTextFull} 类型映射"); - } + case "char(36 char)": return OracleDbType.Char; + } + switch (column.DbTypeText.ToLower()) + { + case "number": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["number(10,2)"]); + return OracleDbType.Decimal; + case "float": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["float(126)"]); + return OracleDbType.Double; + case "interval day to second": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["interval day(2) to second(6)"]); + return OracleDbType.IntervalDS; + case "date": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["date(7)"]); + return OracleDbType.IntervalDS; + case "timestamp": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["timestamp(6)"]); + return OracleDbType.TimeStamp; + case "timestamp with local time zone": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["timestamp(6) with local time zone"]); + return OracleDbType.TimeStampLTZ; + case "blob": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["blob"]); + return OracleDbType.Blob; + case "nvarchar2": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); + return OracleDbType.NVarchar2; + case "varchar2": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); + return OracleDbType.Varchar2; + case "char": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["char(36 char)"]); + return OracleDbType.Char; + case "clob": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); + return OracleDbType.Clob; + case "nclob": + _dicDbToCs.TryAdd(dbfull, _dicDbToCs["nvarchar2(255)"]); + return OracleDbType.NClob; + } + throw new NotImplementedException($"未实现 {column.DbTypeTextFull} 类型映射"); + } - static ConcurrentDictionary _dicDbToCs = new ConcurrentDictionary(); - static OracleDbFirst() { - var defaultDbToCs = new Dictionary() { - { "number(1)", ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, + static ConcurrentDictionary _dicDbToCs = new ConcurrentDictionary(); + static OracleDbFirst() + { + var defaultDbToCs = new Dictionary() { + { "number(1)", ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, - { "number(4)", ("(sbyte?)", "sbyte.Parse({0})", "{0}.ToString()", "sbyte?", typeof(sbyte), typeof(sbyte?), "{0}.Value", "GetInt16") }, - { "number(6)", ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, - { "number(11)", ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, - { "number(21)", ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, + { "number(4)", ("(sbyte?)", "sbyte.Parse({0})", "{0}.ToString()", "sbyte?", typeof(sbyte), typeof(sbyte?), "{0}.Value", "GetInt16") }, + { "number(6)", ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, + { "number(11)", ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, + { "number(21)", ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, - { "number(3)", ("(byte?)", "byte.Parse({0})", "{0}.ToString()", "byte?", typeof(byte), typeof(byte?), "{0}.Value", "GetByte") }, - { "number(5)", ("(ushort?)", "ushort.Parse({0})", "{0}.ToString()", "ushort?", typeof(ushort), typeof(ushort?), "{0}.Value", "GetInt32") }, - { "number(10)", ("(uint?)", "uint.Parse({0})", "{0}.ToString()", "uint?", typeof(uint), typeof(uint?), "{0}.Value", "GetInt64") }, - { "number(20)", ("(ulong?)", "ulong.Parse({0})", "{0}.ToString()", "ulong?", typeof(ulong), typeof(ulong?), "{0}.Value", "GetDecimal") }, + { "number(3)", ("(byte?)", "byte.Parse({0})", "{0}.ToString()", "byte?", typeof(byte), typeof(byte?), "{0}.Value", "GetByte") }, + { "number(5)", ("(ushort?)", "ushort.Parse({0})", "{0}.ToString()", "ushort?", typeof(ushort), typeof(ushort?), "{0}.Value", "GetInt32") }, + { "number(10)", ("(uint?)", "uint.Parse({0})", "{0}.ToString()", "uint?", typeof(uint), typeof(uint?), "{0}.Value", "GetInt64") }, + { "number(20)", ("(ulong?)", "ulong.Parse({0})", "{0}.ToString()", "ulong?", typeof(ulong), typeof(ulong?), "{0}.Value", "GetDecimal") }, - { "float(126)", ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, - { "float(63)", ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, - { "number(10,2)", ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, + { "float(126)", ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, + { "float(63)", ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, + { "number(10,2)", ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, - { "interval day(2) to second(6)", ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, - { "date(7)", ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, - { "timestamp(6)", ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, - { "timestamp(6) with local time zone", ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, + { "interval day(2) to second(6)", ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, + { "date(7)", ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, + { "timestamp(6)", ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, + { "timestamp(6) with local time zone", ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetValue") }, - { "blob", ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { "blob", ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { "nvarchar2(255)", ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { "char(36 char)", ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}.Value", "GetGuid") }, - }; - foreach (var kv in defaultDbToCs) - _dicDbToCs.TryAdd(kv.Key, kv.Value); - } - + { "nvarchar2(255)", ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { "char(36 char)", ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}.Value", "GetGuid") }, + }; + foreach (var kv in defaultDbToCs) + _dicDbToCs.TryAdd(kv.Key, kv.Value); + } - public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; - public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csParse : null; - public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csStringify : null; - public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; - public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csTypeInfo : null; - public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csTypeValue : null; - public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.dataReaderMethod : null; - public List GetDatabases() { - var sql = @" select username from all_users"; - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); - } + public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; + public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csParse : null; + public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csStringify : null; + public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; + public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csTypeInfo : null; + public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.csTypeValue : null; + public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbTypeTextFull, out var trydc) ? trydc.dataReaderMethod : null; - public List GetTablesByDatabase(params string[] database2) { - var loc1 = new List(); - var loc2 = new Dictionary(); - var loc3 = new Dictionary>(); - var database = database2?.ToArray(); + public List GetDatabases() + { + var sql = @" select username from all_users"; + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); + } - if (database == null || database.Any() == false) { - var userUsers = _orm.Ado.ExecuteScalar("select username from user_users")?.ToString(); - if (string.IsNullOrEmpty(userUsers)) return loc1; - database = new[] { userUsers }; - } - var databaseIn = string.Join(",", database.Select(a => _commonUtils.FormatSql("{0}", a))); - var sql = string.Format(@" + public List GetTablesByDatabase(params string[] database2) + { + var loc1 = new List(); + var loc2 = new Dictionary(); + var loc3 = new Dictionary>(); + var database = database2?.ToArray(); + + if (database == null || database.Any() == false) + { + var userUsers = _orm.Ado.ExecuteScalar("select username from user_users")?.ToString(); + if (string.IsNullOrEmpty(userUsers)) return loc1; + database = new[] { userUsers }; + } + var databaseIn = string.Join(",", database.Select(a => _commonUtils.FormatSql("{0}", a))); + var sql = string.Format(@" select a.owner || '.' || a.table_name, a.owner, @@ -159,38 +169,41 @@ b.comments, from all_tables a left join all_tab_comments b on b.owner = a.owner and b.table_name = a.table_name and b.table_type = 'TABLE' where a.owner in ({0})", databaseIn); - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var loc6 = new List(); - var loc66 = new List(); - foreach (var row in ds) { - var table_id = string.Concat(row[0]); - var schema = string.Concat(row[1]); - var table = string.Concat(row[2]); - var comment = string.Concat(row[3]); - var type = string.Concat(row[4]) == "VIEW" ? DbTableType.VIEW : DbTableType.TABLE; - if (database.Length == 1) { - table_id = table_id.Substring(table_id.IndexOf('.') + 1); - schema = ""; - } - loc2.Add(table_id, new DbTableInfo { Id = table_id, Schema = schema, Name = table, Comment = comment, Type = type }); - loc3.Add(table_id, new Dictionary()); - switch (type) { - case DbTableType.TABLE: - case DbTableType.VIEW: - loc6.Add(table.Replace("'", "''")); - break; - case DbTableType.StoreProcedure: - loc66.Add(table.Replace("'", "''")); - break; - } - } - if (loc6.Count == 0) return loc1; - var loc8 = "'" + string.Join("','", loc6.ToArray()) + "'"; - var loc88 = "'" + string.Join("','", loc66.ToArray()) + "'"; + var loc6 = new List(); + var loc66 = new List(); + foreach (var row in ds) + { + var table_id = string.Concat(row[0]); + var schema = string.Concat(row[1]); + var table = string.Concat(row[2]); + var comment = string.Concat(row[3]); + var type = string.Concat(row[4]) == "VIEW" ? DbTableType.VIEW : DbTableType.TABLE; + if (database.Length == 1) + { + table_id = table_id.Substring(table_id.IndexOf('.') + 1); + schema = ""; + } + loc2.Add(table_id, new DbTableInfo { Id = table_id, Schema = schema, Name = table, Comment = comment, Type = type }); + loc3.Add(table_id, new Dictionary()); + switch (type) + { + case DbTableType.TABLE: + case DbTableType.VIEW: + loc6.Add(table.Replace("'", "''")); + break; + case DbTableType.StoreProcedure: + loc66.Add(table.Replace("'", "''")); + break; + } + } + if (loc6.Count == 0) return loc1; + var loc8 = "'" + string.Join("','", loc6.ToArray()) + "'"; + var loc88 = "'" + string.Join("','", loc66.ToArray()) + "'"; - sql = string.Format(@" + sql = string.Format(@" select a.owner || '.' || a.table_name, a.column_name, @@ -206,52 +219,56 @@ from all_tab_cols a left join all_col_comments b on b.owner = a.owner and b.table_name = a.table_name and b.column_name = a.column_name where a.owner in ({1}) and a.table_name in ({0}) ", loc8, databaseIn); - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var ds2 = new List(); - foreach (var row in ds) { - var ds2item = new object[8]; - ds2item[0] = row[0]; - ds2item[1] = row[1]; - ds2item[2] = Regex.Replace(string.Concat(row[2]), @"\(\d+\)", ""); - ds2item[4] = OracleCodeFirst.GetOracleSqlTypeFullName(new object[] { row[1], row[2], row[3], row[4], row[5], row[6] }); - ds2item[5] = string.Concat(row[7]) == "1"; - ds2item[6] = string.Concat(row[8]) == "1"; - ds2item[7] = string.Concat(row[9]); - ds2.Add(ds2item); - } - foreach (var row in ds2) { - string table_id = string.Concat(row[0]); - string column = string.Concat(row[1]); - string type = string.Concat(row[2]); - //long max_length = long.Parse(string.Concat(row[3])); - string sqlType = string.Concat(row[4]); - var m_len = Regex.Match(sqlType, @"\w+\((\d+)"); - int max_length = m_len.Success ? int.Parse(m_len.Groups[1].Value) : -1; - bool is_nullable = string.Concat(row[5]) == "1"; - bool is_identity = string.Concat(row[6]) == "1"; - string comment = string.Concat(row[7]); - if (max_length == 0) max_length = -1; - if (database.Length == 1) { - table_id = table_id.Substring(table_id.IndexOf('.') + 1); - } - loc3[table_id].Add(column, new DbColumnInfo { - Name = column, - MaxLength = max_length, - IsIdentity = is_identity, - IsNullable = is_nullable, - IsPrimary = false, - DbTypeText = type, - DbTypeTextFull = sqlType, - Table = loc2[table_id], - Coment = comment - }); - loc3[table_id][column].DbType = this.GetDbType(loc3[table_id][column]); - loc3[table_id][column].CsType = this.GetCsTypeInfo(loc3[table_id][column]); - } + var ds2 = new List(); + foreach (var row in ds) + { + var ds2item = new object[8]; + ds2item[0] = row[0]; + ds2item[1] = row[1]; + ds2item[2] = Regex.Replace(string.Concat(row[2]), @"\(\d+\)", ""); + ds2item[4] = OracleCodeFirst.GetOracleSqlTypeFullName(new object[] { row[1], row[2], row[3], row[4], row[5], row[6] }); + ds2item[5] = string.Concat(row[7]) == "1"; + ds2item[6] = string.Concat(row[8]) == "1"; + ds2item[7] = string.Concat(row[9]); + ds2.Add(ds2item); + } + foreach (var row in ds2) + { + string table_id = string.Concat(row[0]); + string column = string.Concat(row[1]); + string type = string.Concat(row[2]); + //long max_length = long.Parse(string.Concat(row[3])); + string sqlType = string.Concat(row[4]); + var m_len = Regex.Match(sqlType, @"\w+\((\d+)"); + int max_length = m_len.Success ? int.Parse(m_len.Groups[1].Value) : -1; + bool is_nullable = string.Concat(row[5]) == "1"; + bool is_identity = string.Concat(row[6]) == "1"; + string comment = string.Concat(row[7]); + if (max_length == 0) max_length = -1; + if (database.Length == 1) + { + table_id = table_id.Substring(table_id.IndexOf('.') + 1); + } + loc3[table_id].Add(column, new DbColumnInfo + { + Name = column, + MaxLength = max_length, + IsIdentity = is_identity, + IsNullable = is_nullable, + IsPrimary = false, + DbTypeText = type, + DbTypeTextFull = sqlType, + Table = loc2[table_id], + Coment = comment + }); + loc3[table_id][column].DbType = this.GetDbType(loc3[table_id][column]); + loc3[table_id][column].CsType = this.GetCsTypeInfo(loc3[table_id][column]); + } - sql = string.Format(@" + sql = string.Format(@" select a.owner || '.' || a.table_name, c.column_name, @@ -270,53 +287,59 @@ and a.table_name = c.table_name and a.constraint_type in ('P', 'U') and a.owner in ({1}) and a.table_name in ({0}) ", loc8, databaseIn); - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var indexColumns = new Dictionary>>(); - var uniqueColumns = new Dictionary>>(); - foreach (var row in ds) { - string table_id = string.Concat(row[0]); - string column = string.Concat(row[1]); - string index_id = string.Concat(row[2]); - bool is_unique = string.Concat(row[3]) == "1"; - bool is_primary_key = string.Concat(row[4]) == "1"; - bool is_clustered = string.Concat(row[5]) == "1"; - int is_desc = int.Parse(string.Concat(row[6])); - if (database.Length == 1) { - table_id = table_id.Substring(table_id.IndexOf('.') + 1); - } - if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; - var loc9 = loc3[table_id][column]; - if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; + var indexColumns = new Dictionary>>(); + var uniqueColumns = new Dictionary>>(); + foreach (var row in ds) + { + string table_id = string.Concat(row[0]); + string column = string.Concat(row[1]); + string index_id = string.Concat(row[2]); + bool is_unique = string.Concat(row[3]) == "1"; + bool is_primary_key = string.Concat(row[4]) == "1"; + bool is_clustered = string.Concat(row[5]) == "1"; + int is_desc = int.Parse(string.Concat(row[6])); + if (database.Length == 1) + { + table_id = table_id.Substring(table_id.IndexOf('.') + 1); + } + if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; + var loc9 = loc3[table_id][column]; + if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; - Dictionary> loc10 = null; - List loc11 = null; - if (!indexColumns.TryGetValue(table_id, out loc10)) - indexColumns.Add(table_id, loc10 = new Dictionary>()); - if (!loc10.TryGetValue(index_id, out loc11)) - loc10.Add(index_id, loc11 = new List()); - loc11.Add(loc9); - if (is_unique && !is_primary_key) { - if (!uniqueColumns.TryGetValue(table_id, out loc10)) - uniqueColumns.Add(table_id, loc10 = new Dictionary>()); - if (!loc10.TryGetValue(index_id, out loc11)) - loc10.Add(index_id, loc11 = new List()); - loc11.Add(loc9); - } - } - foreach (string table_id in indexColumns.Keys) { - foreach (var column in indexColumns[table_id]) - loc2[table_id].IndexesDict.Add(column.Key, column.Value); - } - foreach (string table_id in uniqueColumns.Keys) { - foreach (var column in uniqueColumns[table_id]) { - column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); - loc2[table_id].UniquesDict.Add(column.Key, column.Value); - } - } + Dictionary> loc10 = null; + List loc11 = null; + if (!indexColumns.TryGetValue(table_id, out loc10)) + indexColumns.Add(table_id, loc10 = new Dictionary>()); + if (!loc10.TryGetValue(index_id, out loc11)) + loc10.Add(index_id, loc11 = new List()); + loc11.Add(loc9); + if (is_unique && !is_primary_key) + { + if (!uniqueColumns.TryGetValue(table_id, out loc10)) + uniqueColumns.Add(table_id, loc10 = new Dictionary>()); + if (!loc10.TryGetValue(index_id, out loc11)) + loc10.Add(index_id, loc11 = new List()); + loc11.Add(loc9); + } + } + foreach (string table_id in indexColumns.Keys) + { + foreach (var column in indexColumns[table_id]) + loc2[table_id].IndexesDict.Add(column.Key, column.Value); + } + foreach (string table_id in uniqueColumns.Keys) + { + foreach (var column in uniqueColumns[table_id]) + { + column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); + loc2[table_id].UniquesDict.Add(column.Key, column.Value); + } + } - sql = string.Format(@" + sql = string.Format(@" select a.owner || '.' || a.table_name, c.column_name, @@ -352,80 +375,91 @@ and b.owner = d.owner    and b.table_name = d.table_name and a.owner in ({1}) and a.table_name in ({0}) ", loc8, databaseIn); - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var fkColumns = new Dictionary>(); - foreach (var row in ds) { - string table_id = string.Concat(row[0]); - string column = string.Concat(row[1]); - string fk_id = string.Concat(row[2]); - string ref_table_id = string.Concat(row[3]); - bool is_foreign_key = string.Concat(row[4]) == "1"; - string referenced_column = string.Concat(row[5]); - if (database.Length == 1) { - table_id = table_id.Substring(table_id.IndexOf('.') + 1); - ref_table_id = ref_table_id.Substring(ref_table_id.IndexOf('.') + 1); - } - if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; - var loc9 = loc3[table_id][column]; - if (loc2.ContainsKey(ref_table_id) == false) continue; - var loc10 = loc2[ref_table_id]; - var loc11 = loc3[ref_table_id][referenced_column]; + var fkColumns = new Dictionary>(); + foreach (var row in ds) + { + string table_id = string.Concat(row[0]); + string column = string.Concat(row[1]); + string fk_id = string.Concat(row[2]); + string ref_table_id = string.Concat(row[3]); + bool is_foreign_key = string.Concat(row[4]) == "1"; + string referenced_column = string.Concat(row[5]); + if (database.Length == 1) + { + table_id = table_id.Substring(table_id.IndexOf('.') + 1); + ref_table_id = ref_table_id.Substring(ref_table_id.IndexOf('.') + 1); + } + if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; + var loc9 = loc3[table_id][column]; + if (loc2.ContainsKey(ref_table_id) == false) continue; + var loc10 = loc2[ref_table_id]; + var loc11 = loc3[ref_table_id][referenced_column]; - Dictionary loc12 = null; - DbForeignInfo loc13 = null; - if (!fkColumns.TryGetValue(table_id, out loc12)) - fkColumns.Add(table_id, loc12 = new Dictionary()); - if (!loc12.TryGetValue(fk_id, out loc13)) - loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[table_id], ReferencedTable = loc10 }); - loc13.Columns.Add(loc9); - loc13.ReferencedColumns.Add(loc11); - } - foreach (var table_id in fkColumns.Keys) - foreach (var fk in fkColumns[table_id]) - loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); + Dictionary loc12 = null; + DbForeignInfo loc13 = null; + if (!fkColumns.TryGetValue(table_id, out loc12)) + fkColumns.Add(table_id, loc12 = new Dictionary()); + if (!loc12.TryGetValue(fk_id, out loc13)) + loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[table_id], ReferencedTable = loc10 }); + loc13.Columns.Add(loc9); + loc13.ReferencedColumns.Add(loc11); + } + foreach (var table_id in fkColumns.Keys) + foreach (var fk in fkColumns[table_id]) + loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); - foreach (var table_id in loc3.Keys) { - foreach (var loc5 in loc3[table_id].Values) { - loc2[table_id].Columns.Add(loc5); - if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); - if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); - } - } - foreach (var loc4 in loc2.Values) { - if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) { - foreach (var loc5 in loc4.UniquesDict.First().Value) { - loc5.IsPrimary = true; - loc4.Primarys.Add(loc5); - } - } - loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); - loc4.Columns.Sort((c1, c2) => { - int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); - if (compare == 0) { - bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); - bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); - compare = b2.CompareTo(b1); - } - if (compare == 0) compare = c1.Name.CompareTo(c2.Name); - return compare; - }); - loc1.Add(loc4); - } - loc1.Sort((t1, t2) => { - var ret = t1.Schema.CompareTo(t2.Schema); - if (ret == 0) ret = t1.Name.CompareTo(t2.Name); - return ret; - }); + foreach (var table_id in loc3.Keys) + { + foreach (var loc5 in loc3[table_id].Values) + { + loc2[table_id].Columns.Add(loc5); + if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); + if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); + } + } + foreach (var loc4 in loc2.Values) + { + if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) + { + foreach (var loc5 in loc4.UniquesDict.First().Value) + { + loc5.IsPrimary = true; + loc4.Primarys.Add(loc5); + } + } + loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); + loc4.Columns.Sort((c1, c2) => + { + int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); + if (compare == 0) + { + bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); + bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); + compare = b2.CompareTo(b1); + } + if (compare == 0) compare = c1.Name.CompareTo(c2.Name); + return compare; + }); + loc1.Add(loc4); + } + loc1.Sort((t1, t2) => + { + var ret = t1.Schema.CompareTo(t2.Schema); + if (ret == 0) ret = t1.Name.CompareTo(t2.Name); + return ret; + }); - loc2.Clear(); - loc3.Clear(); - return loc1; - } + loc2.Clear(); + loc3.Clear(); + return loc1; + } - public List GetEnumsByDatabase(params string[] database) { - return new List(); - } - } + public List GetEnumsByDatabase(params string[] database) + { + return new List(); + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.Oracle/OracleExpression.cs b/Providers/FreeSql.Provider.Oracle/OracleExpression.cs index f5f333c6..e4752a68 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleExpression.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleExpression.cs @@ -7,393 +7,449 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.Oracle { - class OracleExpression : CommonExpression { +namespace FreeSql.Oracle +{ + class OracleExpression : CommonExpression + { - public OracleExpression(CommonUtils common) : base(common) { } + public OracleExpression(CommonUtils common) : base(common) { } - public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.NodeType) { - case ExpressionType.Convert: - var operandExp = (exp as UnaryExpression)?.Operand; - var gentype = exp.Type.NullableTypeOrThis(); - if (gentype != operandExp.Type.NullableTypeOrThis()) { - switch (exp.Type.NullableTypeOrThis().ToString()) { - //case "System.Boolean": return $"({getExp(operandExp)} not in ('0','false'))"; - case "System.Byte": return $"cast({getExp(operandExp)} as number)"; - case "System.Char": return $"substr(to_char({getExp(operandExp)}), 1, 1)"; - case "System.DateTime": return $"to_timestamp({getExp(operandExp)},'YYYY-MM-DD HH24:MI:SS.FF6')"; - case "System.Decimal": return $"cast({getExp(operandExp)} as number)"; - case "System.Double": return $"cast({getExp(operandExp)} as number)"; - case "System.Int16": - case "System.Int32": - case "System.Int64": - case "System.SByte": return $"cast({getExp(operandExp)} as number)"; - case "System.Single": return $"cast({getExp(operandExp)} as number)"; - case "System.String": return $"to_char({getExp(operandExp)})"; - case "System.UInt16": - case "System.UInt32": - case "System.UInt64": return $"cast({getExp(operandExp)} as number)"; - case "System.Guid": return $"substr(to_char({getExp(operandExp)}), 1, 36)"; - } - } - break; - case ExpressionType.Call: - var callExp = exp as MethodCallExpression; + public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.NodeType) + { + case ExpressionType.Convert: + var operandExp = (exp as UnaryExpression)?.Operand; + var gentype = exp.Type.NullableTypeOrThis(); + if (gentype != operandExp.Type.NullableTypeOrThis()) + { + switch (exp.Type.NullableTypeOrThis().ToString()) + { + //case "System.Boolean": return $"({getExp(operandExp)} not in ('0','false'))"; + case "System.Byte": return $"cast({getExp(operandExp)} as number)"; + case "System.Char": return $"substr(to_char({getExp(operandExp)}), 1, 1)"; + case "System.DateTime": return $"to_timestamp({getExp(operandExp)},'YYYY-MM-DD HH24:MI:SS.FF6')"; + case "System.Decimal": return $"cast({getExp(operandExp)} as number)"; + case "System.Double": return $"cast({getExp(operandExp)} as number)"; + case "System.Int16": + case "System.Int32": + case "System.Int64": + case "System.SByte": return $"cast({getExp(operandExp)} as number)"; + case "System.Single": return $"cast({getExp(operandExp)} as number)"; + case "System.String": return $"to_char({getExp(operandExp)})"; + case "System.UInt16": + case "System.UInt32": + case "System.UInt64": return $"cast({getExp(operandExp)} as number)"; + case "System.Guid": return $"substr(to_char({getExp(operandExp)}), 1, 36)"; + } + } + break; + case ExpressionType.Call: + var callExp = exp as MethodCallExpression; - switch (callExp.Method.Name) { - case "Parse": - case "TryParse": - switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) { - //case "System.Boolean": return $"({getExp(callExp.Arguments[0])} not in ('0','false'))"; - case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as number)"; - case "System.Char": return $"substr(to_char({getExp(callExp.Arguments[0])}), 1, 1)"; - case "System.DateTime": return $"to_timestamp({getExp(callExp.Arguments[0])},'YYYY-MM-DD HH24:MI:SS.FF6')"; - case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as number)"; - case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as number)"; - case "System.Int16": - case "System.Int32": - case "System.Int64": - case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as number)"; - case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as number)"; - case "System.UInt16": - case "System.UInt32": - case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as number)"; - case "System.Guid": return $"substr(to_char({getExp(callExp.Arguments[0])}), 1, 36)"; - } - break; - case "NewGuid": - break; - case "Next": - if (callExp.Object?.Type == typeof(Random)) return "cast(dbms_random.value*1000000000 as smallint)"; - break; - case "NextDouble": - if (callExp.Object?.Type == typeof(Random)) return "dbms_random.value"; - break; - case "Random": - if (callExp.Method.DeclaringType.IsNumberType()) return "dbms_random.value"; - break; - case "ToString": - if (callExp.Object != null) return $"to_char({getExp(callExp.Object)})"; - break; - } + switch (callExp.Method.Name) + { + case "Parse": + case "TryParse": + switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) + { + //case "System.Boolean": return $"({getExp(callExp.Arguments[0])} not in ('0','false'))"; + case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as number)"; + case "System.Char": return $"substr(to_char({getExp(callExp.Arguments[0])}), 1, 1)"; + case "System.DateTime": return $"to_timestamp({getExp(callExp.Arguments[0])},'YYYY-MM-DD HH24:MI:SS.FF6')"; + case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as number)"; + case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as number)"; + case "System.Int16": + case "System.Int32": + case "System.Int64": + case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as number)"; + case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as number)"; + case "System.UInt16": + case "System.UInt32": + case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as number)"; + case "System.Guid": return $"substr(to_char({getExp(callExp.Arguments[0])}), 1, 36)"; + } + break; + case "NewGuid": + break; + case "Next": + if (callExp.Object?.Type == typeof(Random)) return "cast(dbms_random.value*1000000000 as smallint)"; + break; + case "NextDouble": + if (callExp.Object?.Type == typeof(Random)) return "dbms_random.value"; + break; + case "Random": + if (callExp.Method.DeclaringType.IsNumberType()) return "dbms_random.value"; + break; + case "ToString": + if (callExp.Object != null) return $"to_char({getExp(callExp.Object)})"; + break; + } - var objExp = callExp.Object; - var objType = objExp?.Type; - if (objType?.FullName == "System.Byte[]") return null; + var objExp = callExp.Object; + var objType = objExp?.Type; + if (objType?.FullName == "System.Byte[]") return null; - var argIndex = 0; - if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) { - objExp = callExp.Arguments.FirstOrDefault(); - objType = objExp?.Type; - argIndex++; - } - if (objType == null) objType = callExp.Method.DeclaringType; - if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) { - var left = objExp == null ? null : getExp(objExp); - switch (callExp.Method.Name) { - case "Contains": - //判断 in - return $"({getExp(callExp.Arguments[argIndex])}) in {left}"; - } - } - break; - case ExpressionType.NewArrayInit: - var arrExp = exp as NewArrayExpression; - var arrSb = new StringBuilder(); - arrSb.Append("("); - for (var a = 0; a < arrExp.Expressions.Count; a++) { - if (a > 0) arrSb.Append(","); - arrSb.Append(getExp(arrExp.Expressions[a])); - } - if (arrSb.Length == 1) arrSb.Append("NULL"); - return arrSb.Append(")").ToString(); - case ExpressionType.ListInit: - var listExp = exp as ListInitExpression; - var listSb = new StringBuilder(); - listSb.Append("("); - for (var a = 0; a < listExp.Initializers.Count; a++) { - if (listExp.Initializers[a].Arguments.Any() == false) continue; - if (a > 0) listSb.Append(","); - listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); - } - if (listSb.Length == 1) listSb.Append("NULL"); - return listSb.Append(")").ToString(); - case ExpressionType.New: - var newExp = exp as NewExpression; - if (typeof(IList).IsAssignableFrom(newExp.Type)) { - if (newExp.Arguments.Count == 0) return "(NULL)"; - if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; - return getExp(newExp.Arguments[0]); - } - return null; - } - return null; - } + var argIndex = 0; + if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) + { + objExp = callExp.Arguments.FirstOrDefault(); + objType = objExp?.Type; + argIndex++; + } + if (objType == null) objType = callExp.Method.DeclaringType; + if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) + { + var left = objExp == null ? null : getExp(objExp); + switch (callExp.Method.Name) + { + case "Contains": + //判断 in + return $"({getExp(callExp.Arguments[argIndex])}) in {left}"; + } + } + break; + case ExpressionType.NewArrayInit: + var arrExp = exp as NewArrayExpression; + var arrSb = new StringBuilder(); + arrSb.Append("("); + for (var a = 0; a < arrExp.Expressions.Count; a++) + { + if (a > 0) arrSb.Append(","); + arrSb.Append(getExp(arrExp.Expressions[a])); + } + if (arrSb.Length == 1) arrSb.Append("NULL"); + return arrSb.Append(")").ToString(); + case ExpressionType.ListInit: + var listExp = exp as ListInitExpression; + var listSb = new StringBuilder(); + listSb.Append("("); + for (var a = 0; a < listExp.Initializers.Count; a++) + { + if (listExp.Initializers[a].Arguments.Any() == false) continue; + if (a > 0) listSb.Append(","); + listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); + } + if (listSb.Length == 1) listSb.Append("NULL"); + return listSb.Append(")").ToString(); + case ExpressionType.New: + var newExp = exp as NewExpression; + if (typeof(IList).IsAssignableFrom(newExp.Type)) + { + if (newExp.Arguments.Count == 0) return "(NULL)"; + if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; + return getExp(newExp.Arguments[0]); + } + return null; + } + return null; + } - public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Empty": return "''"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Length": return $"length({left})"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Now": return "systimestamp"; - case "UtcNow": return "sys_extract_utc(systimestamp)"; - case "Today": return "trunc(systimestamp)"; - case "MinValue": return "to_timestamp('0001-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS.FF6')"; - case "MaxValue": return "to_timestamp('9999-12-31 23:59:59','YYYY-MM-DD HH24:MI:SS.FF6')"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Date": return $"trunc({left})"; - case "TimeOfDay": return $"({left}-trunc({left}))"; - case "DayOfWeek": return $"case when to_char({left})='7' then 0 else cast(to_char({left}) as number) end"; - case "Day": return $"cast(to_char({left},'DD') as number)"; - case "DayOfYear": return $"cast(to_char({left},'DDD') as number)"; - case "Month": return $"cast(to_char({left},'MM') as number)"; - case "Year": return $"cast(to_char({left},'YYYY') as number)"; - case "Hour": return $"cast(to_char({left},'HH24') as number)"; - case "Minute": return $"cast(to_char({left},'MI') as number)"; - case "Second": return $"cast(to_char({left},'SS') as number)"; - case "Millisecond": return $"cast(to_char({left},'FF3') as number)"; - case "Ticks": return $"cast(to_char({left},'FF7') as number)"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Zero": return "numtodsinterval(0,'second')"; - case "MinValue": return "numtodsinterval(-233720368.5477580,'second')"; - case "MaxValue": return "numtodsinterval(233720368.5477580,'second')"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Days": return $"extract(day from {left})"; - case "Hours": return $"extract(hour from {left})"; - case "Milliseconds": return $"cast(substr(extract(second from {left})-floor(extract(second from {left})),2,3) as number)"; - case "Minutes": return $"extract(minute from {left})"; - case "Seconds": return $"floor(extract(second from {left}))"; - case "Ticks": return $"(extract(day from {left})*86400+extract(hour from {left})*3600+extract(minute from {left})*60+extract(second from {left}))*10000000"; - case "TotalDays": return $"extract(day from {left})"; - case "TotalHours": return $"(extract(day from {left})*24+extract(hour from {left}))"; - case "TotalMilliseconds": return $"(extract(day from {left})*86400+extract(hour from {left})*3600+extract(minute from {left})*60+extract(second from {left}))*1000"; - case "TotalMinutes": return $"(extract(day from {left})*1440+extract(hour from {left})*60+extract(minute from {left}))"; - case "TotalSeconds": return $"(extract(day from {left})*86400+extract(hour from {left})*3600+extract(minute from {left})*60+extract(second from {left}))"; - } - return null; - } + public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Empty": return "''"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Length": return $"length({left})"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Now": return "systimestamp"; + case "UtcNow": return "sys_extract_utc(systimestamp)"; + case "Today": return "trunc(systimestamp)"; + case "MinValue": return "to_timestamp('0001-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS.FF6')"; + case "MaxValue": return "to_timestamp('9999-12-31 23:59:59','YYYY-MM-DD HH24:MI:SS.FF6')"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Date": return $"trunc({left})"; + case "TimeOfDay": return $"({left}-trunc({left}))"; + case "DayOfWeek": return $"case when to_char({left})='7' then 0 else cast(to_char({left}) as number) end"; + case "Day": return $"cast(to_char({left},'DD') as number)"; + case "DayOfYear": return $"cast(to_char({left},'DDD') as number)"; + case "Month": return $"cast(to_char({left},'MM') as number)"; + case "Year": return $"cast(to_char({left},'YYYY') as number)"; + case "Hour": return $"cast(to_char({left},'HH24') as number)"; + case "Minute": return $"cast(to_char({left},'MI') as number)"; + case "Second": return $"cast(to_char({left},'SS') as number)"; + case "Millisecond": return $"cast(to_char({left},'FF3') as number)"; + case "Ticks": return $"cast(to_char({left},'FF7') as number)"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Zero": return "numtodsinterval(0,'second')"; + case "MinValue": return "numtodsinterval(-233720368.5477580,'second')"; + case "MaxValue": return "numtodsinterval(233720368.5477580,'second')"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Days": return $"extract(day from {left})"; + case "Hours": return $"extract(hour from {left})"; + case "Milliseconds": return $"cast(substr(extract(second from {left})-floor(extract(second from {left})),2,3) as number)"; + case "Minutes": return $"extract(minute from {left})"; + case "Seconds": return $"floor(extract(second from {left}))"; + case "Ticks": return $"(extract(day from {left})*86400+extract(hour from {left})*3600+extract(minute from {left})*60+extract(second from {left}))*10000000"; + case "TotalDays": return $"extract(day from {left})"; + case "TotalHours": return $"(extract(day from {left})*24+extract(hour from {left}))"; + case "TotalMilliseconds": return $"(extract(day from {left})*86400+extract(hour from {left})*3600+extract(minute from {left})*60+extract(second from {left}))*1000"; + case "TotalMinutes": return $"(extract(day from {left})*1440+extract(hour from {left})*60+extract(minute from {left}))"; + case "TotalSeconds": return $"(extract(day from {left})*86400+extract(hour from {left})*3600+extract(minute from {left})*60+extract(second from {left}))"; + } + return null; + } - public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "IsNullOrEmpty": - var arg1 = getExp(exp.Arguments[0]); - return $"({arg1} is null or {arg1} = '')"; - case "Concat": - return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); - } - } else { - var left = getExp(exp.Object); - switch (exp.Method.Name) { - case "StartsWith": - case "EndsWith": - case "Contains": - var args0Value = getExp(exp.Arguments[0]); - if (args0Value == "NULL") return $"({left}) IS NULL"; - if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(to_char({args0Value})||'%')")}"; - if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%'||to_char({args0Value}))")}"; - if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; - return $"({left}) LIKE ('%'||to_char({args0Value})||'%')"; - case "ToLower": return $"lower({left})"; - case "ToUpper": return $"upper({left})"; - case "Substring": - var substrArgs1 = getExp(exp.Arguments[0]); - if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); - else substrArgs1 += "+1"; - if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; - return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; - case "IndexOf": - var indexOfFindStr = getExp(exp.Arguments[0]); - if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") { - var locateArgs1 = getExp(exp.Arguments[1]); - if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); - else locateArgs1 += "+1"; - return $"(instr({left}, {indexOfFindStr}, {locateArgs1}, 1)-1)"; - } - return $"(instr({left}, {indexOfFindStr}, 1, 1))-1"; - case "PadLeft": - if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])}, ' ')"; - return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "PadRight": - if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])}, ' ')"; - return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Trim": - case "TrimStart": - case "TrimEnd": - if (exp.Arguments.Count == 0) { - if (exp.Method.Name == "Trim") return $"trim({left})"; - if (exp.Method.Name == "TrimStart") return $"ltrim({left})"; - if (exp.Method.Name == "TrimEnd") return $"rtrim({left})"; - } - foreach (var argsTrim02 in exp.Arguments) { - var argsTrim01s = new[] { argsTrim02 }; - if (argsTrim02.NodeType == ExpressionType.NewArrayInit) { - var arritem = argsTrim02 as NewArrayExpression; - argsTrim01s = arritem.Expressions.ToArray(); - } - foreach (var argsTrim01 in argsTrim01s) { - if (exp.Method.Name == "Trim") left = $"trim(both {getExp(argsTrim01)} from {left})"; - if (exp.Method.Name == "TrimStart") left = $"ltrim({left},{getExp(argsTrim01)})"; - if (exp.Method.Name == "TrimEnd") left = $"rtrim({left},{getExp(argsTrim01)})"; - } - } - return left; - case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "CompareTo": return $"case when {left} = {getExp(exp.Arguments[0])} then 0 when {left} > {getExp(exp.Arguments[0])} then 1 else -1 end"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - } - } - throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.Method.Name) { - case "Abs": return $"abs({getExp(exp.Arguments[0])})"; - case "Sign": return $"sign({getExp(exp.Arguments[0])})"; - case "Floor": return $"floor({getExp(exp.Arguments[0])})"; - case "Ceiling": return $"ceil({getExp(exp.Arguments[0])})"; - case "Round": - if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - return $"round({getExp(exp.Arguments[0])})"; - case "Exp": return $"exp({getExp(exp.Arguments[0])})"; - case "Log": if (exp.Arguments.Count > 1) return $"log({getExp(exp.Arguments[1])},{getExp(exp.Arguments[0])})"; - return $"log(2.7182818284590451,{getExp(exp.Arguments[0])})"; - case "Log10": return $"log(10,{getExp(exp.Arguments[0])})"; - case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; - case "Cos": return $"cos({getExp(exp.Arguments[0])})"; - case "Sin": return $"sin({getExp(exp.Arguments[0])})"; - case "Tan": return $"tan({getExp(exp.Arguments[0])})"; - case "Acos": return $"acos({getExp(exp.Arguments[0])})"; - case "Asin": return $"asin({getExp(exp.Arguments[0])})"; - case "Atan": return $"atan({getExp(exp.Arguments[0])})"; - //case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Truncate": return $"trunc({getExp(exp.Arguments[0])}, 0)"; - } - throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"extract(day from ({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])})))"; - case "DaysInMonth": return $"cast(to_char(last_day(({getExp(exp.Arguments[0])})||'-'||({getExp(exp.Arguments[1])})||'-01'),'DD') as number)"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "IsNullOrEmpty": + var arg1 = getExp(exp.Arguments[0]); + return $"({arg1} is null or {arg1} = '')"; + case "Concat": + return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); + } + } + else + { + var left = getExp(exp.Object); + switch (exp.Method.Name) + { + case "StartsWith": + case "EndsWith": + case "Contains": + var args0Value = getExp(exp.Arguments[0]); + if (args0Value == "NULL") return $"({left}) IS NULL"; + if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(to_char({args0Value})||'%')")}"; + if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%'||to_char({args0Value}))")}"; + if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; + return $"({left}) LIKE ('%'||to_char({args0Value})||'%')"; + case "ToLower": return $"lower({left})"; + case "ToUpper": return $"upper({left})"; + case "Substring": + var substrArgs1 = getExp(exp.Arguments[0]); + if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); + else substrArgs1 += "+1"; + if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; + return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; + case "IndexOf": + var indexOfFindStr = getExp(exp.Arguments[0]); + if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") + { + var locateArgs1 = getExp(exp.Arguments[1]); + if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); + else locateArgs1 += "+1"; + return $"(instr({left}, {indexOfFindStr}, {locateArgs1}, 1)-1)"; + } + return $"(instr({left}, {indexOfFindStr}, 1, 1))-1"; + case "PadLeft": + if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])}, ' ')"; + return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "PadRight": + if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])}, ' ')"; + return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Trim": + case "TrimStart": + case "TrimEnd": + if (exp.Arguments.Count == 0) + { + if (exp.Method.Name == "Trim") return $"trim({left})"; + if (exp.Method.Name == "TrimStart") return $"ltrim({left})"; + if (exp.Method.Name == "TrimEnd") return $"rtrim({left})"; + } + foreach (var argsTrim02 in exp.Arguments) + { + var argsTrim01s = new[] { argsTrim02 }; + if (argsTrim02.NodeType == ExpressionType.NewArrayInit) + { + var arritem = argsTrim02 as NewArrayExpression; + argsTrim01s = arritem.Expressions.ToArray(); + } + foreach (var argsTrim01 in argsTrim01s) + { + if (exp.Method.Name == "Trim") left = $"trim(both {getExp(argsTrim01)} from {left})"; + if (exp.Method.Name == "TrimStart") left = $"ltrim({left},{getExp(argsTrim01)})"; + if (exp.Method.Name == "TrimEnd") left = $"rtrim({left},{getExp(argsTrim01)})"; + } + } + return left; + case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "CompareTo": return $"case when {left} = {getExp(exp.Arguments[0])} then 0 when {left} > {getExp(exp.Arguments[0])} then 1 else -1 end"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + } + } + throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.Method.Name) + { + case "Abs": return $"abs({getExp(exp.Arguments[0])})"; + case "Sign": return $"sign({getExp(exp.Arguments[0])})"; + case "Floor": return $"floor({getExp(exp.Arguments[0])})"; + case "Ceiling": return $"ceil({getExp(exp.Arguments[0])})"; + case "Round": + if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + return $"round({getExp(exp.Arguments[0])})"; + case "Exp": return $"exp({getExp(exp.Arguments[0])})"; + case "Log": + if (exp.Arguments.Count > 1) return $"log({getExp(exp.Arguments[1])},{getExp(exp.Arguments[0])})"; + return $"log(2.7182818284590451,{getExp(exp.Arguments[0])})"; + case "Log10": return $"log(10,{getExp(exp.Arguments[0])})"; + case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; + case "Cos": return $"cos({getExp(exp.Arguments[0])})"; + case "Sin": return $"sin({getExp(exp.Arguments[0])})"; + case "Tan": return $"tan({getExp(exp.Arguments[0])})"; + case "Acos": return $"acos({getExp(exp.Arguments[0])})"; + case "Asin": return $"asin({getExp(exp.Arguments[0])})"; + case "Atan": return $"atan({getExp(exp.Arguments[0])})"; + //case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Truncate": return $"trunc({getExp(exp.Arguments[0])}, 0)"; + } + throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"extract(day from ({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])})))"; + case "DaysInMonth": return $"cast(to_char(last_day(({getExp(exp.Arguments[0])})||'-'||({getExp(exp.Arguments[1])})||'-01'),'DD') as number)"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "IsLeapYear": - var isLeapYearArgs1 = getExp(exp.Arguments[0]); - return $"(mod({isLeapYearArgs1},4)=0 AND mod({isLeapYearArgs1},100)<>0 OR mod({isLeapYearArgs1},400)=0)"; + case "IsLeapYear": + var isLeapYearArgs1 = getExp(exp.Arguments[0]); + return $"(mod({isLeapYearArgs1},4)=0 AND mod({isLeapYearArgs1},100)<>0 OR mod({isLeapYearArgs1},400)=0)"; - case "Parse": return $"to_timestamp({getExp(exp.Arguments[0])},'YYYY-MM-DD HH24:MI:SS.FF6')"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"to_timestamp({getExp(exp.Arguments[0])},'YYYY-MM-DD HH24:MI:SS.FF6')"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"({left}+{args1})"; - case "AddDays": return $"({left}+{args1})"; - case "AddHours": return $"({left}+({args1})/24)"; - case "AddMilliseconds": return $"({left}+({args1})/86400000)"; - case "AddMinutes": return $"({left}+({args1})/1440)"; - case "AddMonths": return $"add_months({left},{args1})"; - case "AddSeconds": return $"({left}+({args1})/86400)"; - case "AddTicks": return $"({left}+({args1})/864000000000)"; - case "AddYears": return $"add_months({left},({args1})*12)"; - case "Subtract": - switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) { - case "System.DateTime": return $"({args1}-{left})"; - case "System.TimeSpan": return $"({left}-{args1})"; - } - break; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"extract(day from ({left}-({getExp(exp.Arguments[0])})))"; - case "ToString": return $"to_char({left},'YYYY-MM-DD HH24:MI:SS.FF6')"; - } - } - throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"extract(day from ({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])})))"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "FromDays": return $"numtodsinterval(({getExp(exp.Arguments[0])})*{(long)60 * 60 * 24},'second')"; - case "FromHours": return $"numtodsinterval(({getExp(exp.Arguments[0])})*{(long)60 * 60},'second')"; - case "FromMilliseconds": return $"numtodsinterval(({getExp(exp.Arguments[0])})/1000,'second')"; - case "FromMinutes": return $"numtodsinterval(({getExp(exp.Arguments[0])})*60,'second')"; - case "FromSeconds": return $"numtodsinterval(({getExp(exp.Arguments[0])}),'second')"; - case "FromTicks": return $"numtodsinterval(({getExp(exp.Arguments[0])})/10000000,'second')"; - case "Parse": return $"cast({getExp(exp.Arguments[0])} as interval day(9) to second(7))"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as interval day(9) to second(7))"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"({left}+{args1})"; - case "Subtract": return $"({left}-({args1}))"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"extract(day from ({left}-({getExp(exp.Arguments[0])})))"; - case "ToString": return $"to_char({left})"; - } - } - throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - //case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))"; - case "ToByte": return $"cast({getExp(exp.Arguments[0])} as number)"; - case "ToChar": return $"substr(to_char({getExp(exp.Arguments[0])}), 1, 1)"; - case "ToDateTime": return $"to_timestamp({getExp(exp.Arguments[0])},'YYYY-MM-DD HH24:MI:SS.FF6')"; - case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as number)"; - case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as number)"; - case "ToInt16": - case "ToInt32": - case "ToInt64": - case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as number)"; - case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as number)"; - case "ToString": return $"to_char({getExp(exp.Arguments[0])})"; - case "ToUInt16": - case "ToUInt32": - case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as number)"; - } - } - throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); - } - } + case "Parse": return $"to_timestamp({getExp(exp.Arguments[0])},'YYYY-MM-DD HH24:MI:SS.FF6')"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"to_timestamp({getExp(exp.Arguments[0])},'YYYY-MM-DD HH24:MI:SS.FF6')"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"({left}+{args1})"; + case "AddDays": return $"({left}+{args1})"; + case "AddHours": return $"({left}+({args1})/24)"; + case "AddMilliseconds": return $"({left}+({args1})/86400000)"; + case "AddMinutes": return $"({left}+({args1})/1440)"; + case "AddMonths": return $"add_months({left},{args1})"; + case "AddSeconds": return $"({left}+({args1})/86400)"; + case "AddTicks": return $"({left}+({args1})/864000000000)"; + case "AddYears": return $"add_months({left},({args1})*12)"; + case "Subtract": + switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) + { + case "System.DateTime": return $"({args1}-{left})"; + case "System.TimeSpan": return $"({left}-{args1})"; + } + break; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"extract(day from ({left}-({getExp(exp.Arguments[0])})))"; + case "ToString": return $"to_char({left},'YYYY-MM-DD HH24:MI:SS.FF6')"; + } + } + throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"extract(day from ({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])})))"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + case "FromDays": return $"numtodsinterval(({getExp(exp.Arguments[0])})*{(long)60 * 60 * 24},'second')"; + case "FromHours": return $"numtodsinterval(({getExp(exp.Arguments[0])})*{(long)60 * 60},'second')"; + case "FromMilliseconds": return $"numtodsinterval(({getExp(exp.Arguments[0])})/1000,'second')"; + case "FromMinutes": return $"numtodsinterval(({getExp(exp.Arguments[0])})*60,'second')"; + case "FromSeconds": return $"numtodsinterval(({getExp(exp.Arguments[0])}),'second')"; + case "FromTicks": return $"numtodsinterval(({getExp(exp.Arguments[0])})/10000000,'second')"; + case "Parse": return $"cast({getExp(exp.Arguments[0])} as interval day(9) to second(7))"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as interval day(9) to second(7))"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"({left}+{args1})"; + case "Subtract": return $"({left}-({args1}))"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"extract(day from ({left}-({getExp(exp.Arguments[0])})))"; + case "ToString": return $"to_char({left})"; + } + } + throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + //case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))"; + case "ToByte": return $"cast({getExp(exp.Arguments[0])} as number)"; + case "ToChar": return $"substr(to_char({getExp(exp.Arguments[0])}), 1, 1)"; + case "ToDateTime": return $"to_timestamp({getExp(exp.Arguments[0])},'YYYY-MM-DD HH24:MI:SS.FF6')"; + case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as number)"; + case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as number)"; + case "ToInt16": + case "ToInt32": + case "ToInt64": + case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as number)"; + case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as number)"; + case "ToString": return $"to_char({getExp(exp.Arguments[0])})"; + case "ToUInt16": + case "ToUInt32": + case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as number)"; + } + } + throw new Exception($"OracleExpression 未实现函数表达式 {exp} 解析"); + } + } } diff --git a/Providers/FreeSql.Provider.Oracle/OracleExtensions.cs b/Providers/FreeSql.Provider.Oracle/OracleExtensions.cs index 35c61de6..1d93ccaa 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleExtensions.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleExtensions.cs @@ -1,11 +1,12 @@ -public static partial class FreeSqlGlobalExtensions { +public static partial class FreeSqlGlobalExtensions +{ - /// - /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 - /// - /// - /// - /// - public static string FormatOracleSQL(this string that, params object[] args) => _oracleAdo.Addslashes(that, args); - static FreeSql.Oracle.OracleAdo _oracleAdo = new FreeSql.Oracle.OracleAdo(); + /// + /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 + /// + /// + /// + /// + public static string FormatOracleSQL(this string that, params object[] args) => _oracleAdo.Addslashes(that, args); + static FreeSql.Oracle.OracleAdo _oracleAdo = new FreeSql.Oracle.OracleAdo(); } diff --git a/Providers/FreeSql.Provider.Oracle/OracleProvider.cs b/Providers/FreeSql.Provider.Oracle/OracleProvider.cs index 16ae24c3..28ad4744 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleProvider.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleProvider.cs @@ -5,50 +5,55 @@ using System; using System.Collections.Generic; using System.Data.Common; -namespace FreeSql.Oracle { +namespace FreeSql.Oracle +{ - public class OracleProvider : IFreeSql { + public class OracleProvider : IFreeSql + { - public ISelect Select() where T1 : class => new OracleSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public ISelect Select(object dywhere) where T1 : class => new OracleSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IInsert Insert() where T1 : class => new OracleInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); - public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); - public IUpdate Update() where T1 : class => new OracleUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IUpdate Update(object dywhere) where T1 : class => new OracleUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IDelete Delete() where T1 : class => new OracleDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IDelete Delete(object dywhere) where T1 : class => new OracleDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public ISelect Select() where T1 : class => new OracleSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public ISelect Select(object dywhere) where T1 : class => new OracleSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IInsert Insert() where T1 : class => new OracleInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); + public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); + public IUpdate Update() where T1 : class => new OracleUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IUpdate Update(object dywhere) where T1 : class => new OracleUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IDelete Delete() where T1 : class => new OracleDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IDelete Delete(object dywhere) where T1 : class => new OracleDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IAdo Ado { get; } - public IAop Aop { get; } - public ICodeFirst CodeFirst { get; } - public IDbFirst DbFirst { get; } - public OracleProvider(string masterConnectionString, string[] slaveConnectionString) { - this.InternalCommonUtils = new OracleUtils(this); - this.InternalCommonExpression = new OracleExpression(this.InternalCommonUtils); + public IAdo Ado { get; } + public IAop Aop { get; } + public ICodeFirst CodeFirst { get; } + public IDbFirst DbFirst { get; } + public OracleProvider(string masterConnectionString, string[] slaveConnectionString) + { + this.InternalCommonUtils = new OracleUtils(this); + this.InternalCommonExpression = new OracleExpression(this.InternalCommonUtils); - this.Ado = new OracleAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); - this.Aop = new AopProvider(); + this.Ado = new OracleAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); + this.Aop = new AopProvider(); - this.DbFirst = new OracleDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - this.CodeFirst = new OracleCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - } + this.DbFirst = new OracleDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + this.CodeFirst = new OracleCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + } - internal CommonUtils InternalCommonUtils { get; } - internal CommonExpression InternalCommonExpression { get; } + internal CommonUtils InternalCommonUtils { get; } + internal CommonExpression InternalCommonExpression { get; } - public void Transaction(Action handler) => Ado.Transaction(handler); + public void Transaction(Action handler) => Ado.Transaction(handler); - public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); + public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); - ~OracleProvider() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - (this.Ado as AdoProvider)?.Dispose(); - } - } + ~OracleProvider() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + (this.Ado as AdoProvider)?.Dispose(); + } + } } diff --git a/Providers/FreeSql.Provider.Oracle/OracleUtils.cs b/Providers/FreeSql.Provider.Oracle/OracleUtils.cs index 60b73a7c..c9deb887 100644 --- a/Providers/FreeSql.Provider.Oracle/OracleUtils.cs +++ b/Providers/FreeSql.Provider.Oracle/OracleUtils.cs @@ -7,70 +7,82 @@ using System.Data.Common; using System.Linq.Expressions; using System.Text; -namespace FreeSql.Oracle { +namespace FreeSql.Oracle +{ - class OracleUtils : CommonUtils { - public OracleUtils(IFreeSql orm) : base(orm) { - } + class OracleUtils : CommonUtils + { + public OracleUtils(IFreeSql orm) : base(orm) + { + } - public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) { - if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; - var dbtype = (OracleDbType)_orm.CodeFirst.GetDbInfo(type)?.type; - if (dbtype == OracleDbType.Boolean) { - if (value == null) value = null; - else value = (bool)value == true ? 1 : 0; - dbtype = OracleDbType.Int16; - } - var ret = new OracleParameter { ParameterName = QuoteParamterName(parameterName), OracleDbType = dbtype, Value = value }; - _params?.Add(ret); - return ret; - } + public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) + { + if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; + var dbtype = (OracleDbType)_orm.CodeFirst.GetDbInfo(type)?.type; + if (dbtype == OracleDbType.Boolean) + { + if (value == null) value = null; + else value = (bool)value == true ? 1 : 0; + dbtype = OracleDbType.Int16; + } + var ret = new OracleParameter { ParameterName = QuoteParamterName(parameterName), OracleDbType = dbtype, Value = value }; + _params?.Add(ret); + return ret; + } - public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => - Utils.GetDbParamtersByObject(sql, obj, ":", (name, type, value) => { - var dbtype = (OracleDbType)_orm.CodeFirst.GetDbInfo(type)?.type; - if (dbtype == OracleDbType.Boolean) { - if (value == null) value = null; - else value = (bool)value == true ? 1 : 0; - dbtype = OracleDbType.Int16; - } - var ret = new OracleParameter { ParameterName = $":{name}", OracleDbType = dbtype, Value = value }; - return ret; - }); + public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => + Utils.GetDbParamtersByObject(sql, obj, ":", (name, type, value) => + { + var dbtype = (OracleDbType)_orm.CodeFirst.GetDbInfo(type)?.type; + if (dbtype == OracleDbType.Boolean) + { + if (value == null) value = null; + else value = (bool)value == true ? 1 : 0; + dbtype = OracleDbType.Int16; + } + var ret = new OracleParameter { ParameterName = $":{name}", OracleDbType = dbtype, Value = value }; + return ret; + }); - public override string FormatSql(string sql, params object[] args) => sql?.FormatOracleSQL(args); - public override string QuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"\"{nametrim.Trim('"').Replace(".", "\".\"")}\""; - } - public override string TrimQuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"{nametrim.Trim('"').Replace("\".\"", ".").Replace(".\"", ".")}"; - } - public override string QuoteParamterName(string name) => $":{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; - public override string IsNull(string sql, object value) => $"nvl({sql}, {value})"; - public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; - public override string Mod(string left, string right, Type leftType, Type rightType) => $"mod({left}, {right})"; + public override string FormatSql(string sql, params object[] args) => sql?.FormatOracleSQL(args); + public override string QuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"\"{nametrim.Trim('"').Replace(".", "\".\"")}\""; + } + public override string TrimQuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"{nametrim.Trim('"').Replace("\".\"", ".").Replace(".\"", ".")}"; + } + public override string QuoteParamterName(string name) => $":{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; + public override string IsNull(string sql, object value) => $"nvl({sql}, {value})"; + public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; + public override string Mod(string left, string right, Type leftType, Type rightType) => $"mod({left}, {right})"; - public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; - public override string QuoteReadColumn(Type type, string columnName) => columnName; + public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; + public override string QuoteReadColumn(Type type, string columnName) => columnName; - public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) { - if (value == null) return "NULL"; - if (type == typeof(byte[])) { - var bytes = value as byte[]; - var sb = new StringBuilder().Append("rawtohex('0x"); - foreach (var vc in bytes) { - if (vc < 10) sb.Append("0"); - sb.Append(vc.ToString("X")); - } - return sb.Append("')").ToString(); - } - return FormatSql("{0}", value, 1); - } - } + public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) + { + if (value == null) return "NULL"; + if (type == typeof(byte[])) + { + var bytes = value as byte[]; + var sb = new StringBuilder().Append("rawtohex('0x"); + foreach (var vc in bytes) + { + if (vc < 10) sb.Append("0"); + sb.Append(vc.ToString("X")); + } + return sb.Append("')").ToString(); + } + return FormatSql("{0}", value, 1); + } + } } diff --git a/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLDelete.cs b/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLDelete.cs index e7011753..251cc918 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLDelete.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLDelete.cs @@ -5,74 +5,91 @@ using System.Data; using System.Text; using System.Threading.Tasks; -namespace FreeSql.PostgreSQL.Curd { +namespace FreeSql.PostgreSQL.Curd +{ - class PostgreSQLDelete : Internal.CommonProvider.DeleteProvider where T1 : class { - public PostgreSQLDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + class PostgreSQLDelete : Internal.CommonProvider.DeleteProvider where T1 : class + { + public PostgreSQLDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override List ExecuteDeleted() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + public override List ExecuteDeleted() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async public override Task> ExecuteDeletedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async public override Task> ExecuteDeletedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - } + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + } } diff --git a/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLInsert.cs b/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLInsert.cs index 40e48e7c..3038a2c2 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLInsert.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLInsert.cs @@ -6,159 +6,200 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.PostgreSQL.Curd { +namespace FreeSql.PostgreSQL.Curd +{ - class PostgreSQLInsert : Internal.CommonProvider.InsertProvider where T1 : class { - public PostgreSQLInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) - : base(orm, commonUtils, commonExpression) { - } + class PostgreSQLInsert : Internal.CommonProvider.InsertProvider where T1 : class + { + public PostgreSQLInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + : base(orm, commonUtils, commonExpression) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(5000, 3000); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(5000, 3000); - public override long ExecuteIdentity() => base.SplitExecuteIdentity(5000, 3000); - public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(5000, 3000); - public override List ExecuteInserted() => base.SplitExecuteInserted(5000, 3000); - public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(5000, 3000); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(5000, 3000); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(5000, 3000); + public override long ExecuteIdentity() => base.SplitExecuteIdentity(5000, 3000); + public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(5000, 3000); + public override List ExecuteInserted() => base.SplitExecuteInserted(5000, 3000); + public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(5000, 3000); - protected override long RawExecuteIdentity() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + protected override long RawExecuteIdentity() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - long ret = 0; - Exception exception = null; - Aop.CurdBeforeEventArgs before = null; + long ret = 0; + Exception exception = null; + Aop.CurdBeforeEventArgs before = null; - var identCols = _table.Columns.Where(a => a.Value.Attribute.IsIdentity == true); - if (identCols.Any() == false) { - before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - try { - ret = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return 0; - } - sql = string.Concat(sql, " RETURNING ", _commonUtils.QuoteSqlName(identCols.First().Value.Attribute.Name)); - before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - try { - long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out ret); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task RawExecuteIdentityAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + var identCols = _table.Columns.Where(a => a.Value.Attribute.IsIdentity == true); + if (identCols.Any() == false) + { + before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + try + { + ret = _orm.Ado.ExecuteNonQuery(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return 0; + } + sql = string.Concat(sql, " RETURNING ", _commonUtils.QuoteSqlName(identCols.First().Value.Attribute.Name)); + before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + try + { + long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out ret); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task RawExecuteIdentityAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - long ret = 0; - Exception exception = null; - Aop.CurdBeforeEventArgs before = null; + long ret = 0; + Exception exception = null; + Aop.CurdBeforeEventArgs before = null; - var identCols = _table.Columns.Where(a => a.Value.Attribute.IsIdentity == true); - if (identCols.Any() == false) { - before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - try { - ret = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return 0; - } - sql = string.Concat(sql, " RETURNING ", _commonUtils.QuoteSqlName(identCols.First().Value.Attribute.Name)); - before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - try { - long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out ret); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } + var identCols = _table.Columns.Where(a => a.Value.Attribute.IsIdentity == true); + if (identCols.Any() == false) + { + before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + try + { + ret = await _orm.Ado.ExecuteNonQueryAsync(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return 0; + } + sql = string.Concat(sql, " RETURNING ", _commonUtils.QuoteSqlName(identCols.First().Value.Attribute.Name)); + before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + try + { + long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out ret); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } - protected override List RawExecuteInserted() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + protected override List RawExecuteInserted() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task> RawExecuteInsertedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task> RawExecuteInsertedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - } + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + } } diff --git a/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLSelect.cs b/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLSelect.cs index d51e7fa7..d58b098e 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLSelect.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLSelect.cs @@ -6,125 +6,147 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.PostgreSQL.Curd { +namespace FreeSql.PostgreSQL.Curd +{ - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class { + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class + { - internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) { - if (_orm.CodeFirst.IsAutoSyncStructure) - _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); + internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) + { + if (_orm.CodeFirst.IsAutoSyncStructure) + _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); - var sb = new StringBuilder(); - var sbnav = new StringBuilder(); - sb.Append(_select); - if (_distinct) sb.Append("DISTINCT "); - sb.Append(field).Append(" \r\nFROM "); - var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); - var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); - for (var a = 0; a < tbsfrom.Length; a++) { - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); - if (tbsjoin.Length > 0) { - //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 - for (var b = 1; b < tbsfrom.Length; b++) { - sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); - if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); - else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); - } - break; - } else { - if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); - if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); - } - if (a < tbsfrom.Length - 1) sb.Append(", "); - } - foreach (var tb in tbsjoin) { - if (tb.Type == SelectTableInfoType.Parent) continue; - switch (tb.Type) { - case SelectTableInfoType.LeftJoin: - sb.Append(" \r\nLEFT JOIN "); - break; - case SelectTableInfoType.InnerJoin: - sb.Append(" \r\nINNER JOIN "); - break; - case SelectTableInfoType.RightJoin: - sb.Append(" \r\nRIGHT JOIN "); - break; - } - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); - if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); - } - if (_join.Length > 0) sb.Append(_join); + var sb = new StringBuilder(); + var sbnav = new StringBuilder(); + sb.Append(_select); + if (_distinct) sb.Append("DISTINCT "); + sb.Append(field).Append(" \r\nFROM "); + var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); + var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); + for (var a = 0; a < tbsfrom.Length; a++) + { + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); + if (tbsjoin.Length > 0) + { + //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 + for (var b = 1; b < tbsfrom.Length; b++) + { + sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); + if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); + else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); + } + break; + } + else + { + if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); + if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); + } + if (a < tbsfrom.Length - 1) sb.Append(", "); + } + foreach (var tb in tbsjoin) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + switch (tb.Type) + { + case SelectTableInfoType.LeftJoin: + sb.Append(" \r\nLEFT JOIN "); + break; + case SelectTableInfoType.InnerJoin: + sb.Append(" \r\nINNER JOIN "); + break; + case SelectTableInfoType.RightJoin: + sb.Append(" \r\nRIGHT JOIN "); + break; + } + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); + if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); + } + if (_join.Length > 0) sb.Append(_join); - sbnav.Append(_where); - foreach (var tb in _tables) { - if (tb.Type == SelectTableInfoType.Parent) continue; - if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) - sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); - } - if (sbnav.Length > 0) { - sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); - } - if (string.IsNullOrEmpty(_groupby) == false) { - sb.Append(_groupby); - if (string.IsNullOrEmpty(_having) == false) - sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); - } - sb.Append(_orderby); - if (_limit > 0) - sb.Append(" \r\nlimit ").Append(_limit); - if (_skip > 0) - sb.Append(" \r\noffset ").Append(_skip); + sbnav.Append(_where); + foreach (var tb in _tables) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) + sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); + } + if (sbnav.Length > 0) + { + sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); + } + if (string.IsNullOrEmpty(_groupby) == false) + { + sb.Append(_groupby); + if (string.IsNullOrEmpty(_having) == false) + sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); + } + sb.Append(_orderby); + if (_limit > 0) + sb.Append(" \r\nlimit ").Append(_limit); + if (_skip > 0) + sb.Append(" \r\noffset ").Append(_skip); - sbnav.Clear(); - return sb.ToString(); - } + sbnav.Clear(); + return sb.ToString(); + } - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class { - public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new PostgreSQLSelect(_orm, _commonUtils, _commonExpression, null); PostgreSQLSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class PostgreSQLSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class + { + public PostgreSQLSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => PostgreSQLSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } } diff --git a/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLUpdate.cs b/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLUpdate.cs index 985faca3..ad9fce0b 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLUpdate.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/Curd/PostgreSQLUpdate.cs @@ -7,113 +7,136 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.PostgreSQL.Curd { +namespace FreeSql.PostgreSQL.Curd +{ - class PostgreSQLUpdate : Internal.CommonProvider.UpdateProvider where T1 : class { + class PostgreSQLUpdate : Internal.CommonProvider.UpdateProvider where T1 : class + { - public PostgreSQLUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + public PostgreSQLUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 3000); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 3000); - public override List ExecuteUpdated() => base.SplitExecuteUpdated(500, 3000); - public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(500, 3000); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 3000); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 3000); + public override List ExecuteUpdated() => base.SplitExecuteUpdated(500, 3000); + public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(500, 3000); - protected override List RawExecuteUpdated() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + protected override List RawExecuteUpdated() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var dbParms = _params.Concat(_paramsSource).ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); - ValidateVersionAndThrow(ret.Count); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task> RawExecuteUpdatedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var dbParms = _params.Concat(_paramsSource).ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); + ValidateVersionAndThrow(ret.Count); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task> RawExecuteUpdatedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(sql).Append(" RETURNING "); + var sb = new StringBuilder(); + sb.Append(sql).Append(" RETURNING "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } - sql = sb.ToString(); - var dbParms = _params.Concat(_paramsSource).ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - ValidateVersionAndThrow(ret.Count); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } + sql = sb.ToString(); + var dbParms = _params.Concat(_paramsSource).ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + ValidateVersionAndThrow(ret.Count); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } - protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) { - if (_table.Primarys.Length == 1) { - caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); - return; - } - caseWhen.Append("("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) caseWhen.Append(" || "); - caseWhen.Append(_commonUtils.QuoteReadColumn(pk.Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))).Append("::varchar"); - ++pkidx; - } - caseWhen.Append(")"); - } + protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) + { + if (_table.Primarys.Length == 1) + { + caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); + return; + } + caseWhen.Append("("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) caseWhen.Append(" || "); + caseWhen.Append(_commonUtils.QuoteReadColumn(pk.Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))).Append("::varchar"); + ++pkidx; + } + caseWhen.Append(")"); + } - protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) { - if (_table.Primarys.Length == 1) { - sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); - return; - } - sb.Append("("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) sb.Append(" || "); - sb.Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))).Append("::varchar"); - ++pkidx; - } - sb.Append(")"); - } - } + protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) + { + if (_table.Primarys.Length == 1) + { + sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); + return; + } + sb.Append("("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) sb.Append(" || "); + sb.Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))).Append("::varchar"); + ++pkidx; + } + sb.Append(")"); + } + } } diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLAdo.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLAdo.cs index b3940097..0c3b492e 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLAdo.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLAdo.cs @@ -9,69 +9,80 @@ using System.Data.Common; using System.Text; using System.Threading; -namespace FreeSql.PostgreSQL { - class PostgreSQLAdo : FreeSql.Internal.CommonProvider.AdoProvider { - public PostgreSQLAdo() : base(DataType.PostgreSQL) { } - public PostgreSQLAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.PostgreSQL) { - base._util = util; - if (!string.IsNullOrEmpty(masterConnectionString)) - MasterPool = new PostgreSQLConnectionPool("主库", masterConnectionString, null, null); - if (slaveConnectionStrings != null) { - foreach (var slaveConnectionString in slaveConnectionStrings) { - var slavePool = new PostgreSQLConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); - SlavePools.Add(slavePool); - } - } - } +namespace FreeSql.PostgreSQL +{ + class PostgreSQLAdo : FreeSql.Internal.CommonProvider.AdoProvider + { + public PostgreSQLAdo() : base(DataType.PostgreSQL) { } + public PostgreSQLAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.PostgreSQL) + { + base._util = util; + if (!string.IsNullOrEmpty(masterConnectionString)) + MasterPool = new PostgreSQLConnectionPool("主库", masterConnectionString, null, null); + if (slaveConnectionStrings != null) + { + foreach (var slaveConnectionString in slaveConnectionStrings) + { + var slavePool = new PostgreSQLConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); + SlavePools.Add(slavePool); + } + } + } - static DateTime dt1970 = new DateTime(1970, 1, 1); - public override object AddslashesProcessParam(object param, Type mapType) { - if (param == null) return "NULL"; - if (mapType != null && mapType != param.GetType()) - param = Utils.GetDataReaderValue(mapType, param); - bool isdic = false; - if (param is bool || param is bool?) - return (bool)param ? "'t'" : "'f'"; - else if (param is string || param is char) - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - else if (param is Enum) - return ((Enum)param).ToInt64(); - else if (decimal.TryParse(string.Concat(param), out var trydec)) - return param; - else if (param is DateTime || param is DateTime?) - return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.ffffff"), "'"); - else if (param is TimeSpan || param is TimeSpan?) - return ((TimeSpan)param).Ticks / 10; - else if (param is JToken || param is JObject || param is JArray) - return string.Concat("'", param.ToString().Replace("'", "''"), "'::jsonb"); - else if ((isdic = param is Dictionary) || - param is IEnumerable>) { - var pgdics = isdic ? param as Dictionary : - param as IEnumerable>; - if (pgdics == null) return string.Concat("''::hstore"); - var pghstore = new StringBuilder(); - pghstore.Append("'"); - foreach (var dic in pgdics) - pghstore.Append("\"").Append(dic.Key.Replace("'", "''")).Append("\"=>") - .Append(dic.Key.Replace("'", "''")).Append(","); - return pghstore.Append("'::hstore"); - } else if (param is IEnumerable) { - var sb = new StringBuilder(); - var ie = param as IEnumerable; - foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); - return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); - } - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - } + static DateTime dt1970 = new DateTime(1970, 1, 1); + public override object AddslashesProcessParam(object param, Type mapType) + { + if (param == null) return "NULL"; + if (mapType != null && mapType != param.GetType()) + param = Utils.GetDataReaderValue(mapType, param); + bool isdic = false; + if (param is bool || param is bool?) + return (bool)param ? "'t'" : "'f'"; + else if (param is string || param is char) + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + else if (param is Enum) + return ((Enum)param).ToInt64(); + else if (decimal.TryParse(string.Concat(param), out var trydec)) + return param; + else if (param is DateTime || param is DateTime?) + return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.ffffff"), "'"); + else if (param is TimeSpan || param is TimeSpan?) + return ((TimeSpan)param).Ticks / 10; + else if (param is JToken || param is JObject || param is JArray) + return string.Concat("'", param.ToString().Replace("'", "''"), "'::jsonb"); + else if ((isdic = param is Dictionary) || + param is IEnumerable>) + { + var pgdics = isdic ? param as Dictionary : + param as IEnumerable>; + if (pgdics == null) return string.Concat("''::hstore"); + var pghstore = new StringBuilder(); + pghstore.Append("'"); + foreach (var dic in pgdics) + pghstore.Append("\"").Append(dic.Key.Replace("'", "''")).Append("\"=>") + .Append(dic.Key.Replace("'", "''")).Append(","); + return pghstore.Append("'::hstore"); + } + else if (param is IEnumerable) + { + var sb = new StringBuilder(); + var ie = param as IEnumerable; + foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); + return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); + } + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + } - protected override DbCommand CreateCommand() { - return new NpgsqlCommand(); - } + protected override DbCommand CreateCommand() + { + return new NpgsqlCommand(); + } - protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) { - (pool as PostgreSQLConnectionPool).Return(conn, ex); - } + protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) + { + (pool as PostgreSQLConnectionPool).Return(conn, ex); + } - protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); - } + protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLConnectionPool.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLConnectionPool.cs index 3eba3ebf..cd145f8b 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLConnectionPool.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLConnectionPool.cs @@ -9,178 +9,221 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; -namespace FreeSql.PostgreSQL { +namespace FreeSql.PostgreSQL +{ - class PostgreSQLConnectionPool : ObjectPool { + class PostgreSQLConnectionPool : ObjectPool + { - internal Action availableHandler; - internal Action unavailableHandler; + internal Action availableHandler; + internal Action unavailableHandler; - public PostgreSQLConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) { - var policy = new PostgreSQLConnectionPoolPolicy { - _pool = this, - Name = name - }; - this.Policy = policy; - policy.ConnectionString = connectionString; + public PostgreSQLConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) + { + var policy = new PostgreSQLConnectionPoolPolicy + { + _pool = this, + Name = name + }; + this.Policy = policy; + policy.ConnectionString = connectionString; - this.availableHandler = availableHandler; - this.unavailableHandler = unavailableHandler; - } + this.availableHandler = availableHandler; + this.unavailableHandler = unavailableHandler; + } - public void Return(Object obj, Exception exception, bool isRecreate = false) { - if (exception != null && exception is NpgsqlException) { + public void Return(Object obj, Exception exception, bool isRecreate = false) + { + if (exception != null && exception is NpgsqlException) + { - if (exception is System.IO.IOException) { + if (exception is System.IO.IOException) + { - base.SetUnavailable(exception); + base.SetUnavailable(exception); - } else if (obj.Value.Ping() == false) { + } + else if (obj.Value.Ping() == false) + { - base.SetUnavailable(exception); - } - } - base.Return(obj, isRecreate); - } - } + base.SetUnavailable(exception); + } + } + base.Return(obj, isRecreate); + } + } - class PostgreSQLConnectionPoolPolicy : IPolicy { + class PostgreSQLConnectionPoolPolicy : IPolicy + { - internal PostgreSQLConnectionPool _pool; - public string Name { get; set; } = "PostgreSQL NpgsqlConnection 对象池"; - public int PoolSize { get; set; } = 50; - public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); - public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; - public int AsyncGetCapacity { get; set; } = 10000; - public bool IsThrowGetTimeoutException { get; set; } = true; - public int CheckAvailableInterval { get; set; } = 5; + internal PostgreSQLConnectionPool _pool; + public string Name { get; set; } = "PostgreSQL NpgsqlConnection 对象池"; + public int PoolSize { get; set; } = 50; + public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); + public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; + public int AsyncGetCapacity { get; set; } = 10000; + public bool IsThrowGetTimeoutException { get; set; } = true; + public int CheckAvailableInterval { get; set; } = 5; - static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - private string _connectionString; - public string ConnectionString { - get => _connectionString; - set { - _connectionString = value ?? ""; + static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + private string _connectionString; + public string ConnectionString + { + get => _connectionString; + set + { + _connectionString = value ?? ""; - var pattern = @"Max(imum)?\s*pool\s*size\s*=\s*(\d+)"; - Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success == false || int.TryParse(m.Groups[2].Value, out var poolsize) == false || poolsize <= 0) poolsize = 50; - var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); - PoolSize = poolsize + connStrIncr; - _connectionString = m.Success ? - Regex.Replace(_connectionString, pattern, $"Maximum pool size={PoolSize}", RegexOptions.IgnoreCase) : - $"{_connectionString};Maximum pool size={PoolSize}"; + var pattern = @"Max(imum)?\s*pool\s*size\s*=\s*(\d+)"; + Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success == false || int.TryParse(m.Groups[2].Value, out var poolsize) == false || poolsize <= 0) poolsize = 50; + var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); + PoolSize = poolsize + connStrIncr; + _connectionString = m.Success ? + Regex.Replace(_connectionString, pattern, $"Maximum pool size={PoolSize}", RegexOptions.IgnoreCase) : + $"{_connectionString};Maximum pool size={PoolSize}"; - pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - var minPoolSize = 0; - pattern = @"Min(imum)?\s*pool\s*size\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - minPoolSize = int.Parse(m.Groups[2].Value); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + var minPoolSize = 0; + pattern = @"Min(imum)?\s*pool\s*size\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + minPoolSize = int.Parse(m.Groups[2].Value); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); - } - } + FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); + } + } - public bool OnCheckAvailable(Object obj) { - if (obj.Value.State == ConnectionState.Closed) obj.Value.Open(); - return obj.Value.Ping(true); - } + public bool OnCheckAvailable(Object obj) + { + if (obj.Value.State == ConnectionState.Closed) obj.Value.Open(); + return obj.Value.Ping(true); + } - public DbConnection OnCreate() { - var conn = new NpgsqlConnection(_connectionString); - return conn; - } + public DbConnection OnCreate() + { + var conn = new NpgsqlConnection(_connectionString); + return conn; + } - public void OnDestroy(DbConnection obj) { - if (obj.State != ConnectionState.Closed) obj.Close(); - obj.Dispose(); - } + public void OnDestroy(DbConnection obj) + { + if (obj.State != ConnectionState.Closed) obj.Close(); + obj.Dispose(); + } - public void OnGet(Object obj) { + public void OnGet(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) + { - try { - obj.Value.Open(); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + obj.Value.Open(); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - async public Task OnGetAsync(Object obj) { + async public Task OnGetAsync(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) + { - try { - await obj.Value.OpenAsync(); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + await obj.Value.OpenAsync(); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - public void OnGetTimeout() { + public void OnGetTimeout() + { - } + } - public void OnReturn(Object obj) { + public void OnReturn(Object obj) + { - } + } - public void OnAvailable() { - _pool.availableHandler?.Invoke(); - } + public void OnAvailable() + { + _pool.availableHandler?.Invoke(); + } - public void OnUnavailable() { - _pool.unavailableHandler?.Invoke(); - } - } + public void OnUnavailable() + { + _pool.unavailableHandler?.Invoke(); + } + } - static class DbConnectionExtensions { + static class DbConnectionExtensions + { - static DbCommand PingCommand(DbConnection conn) { - var cmd = conn.CreateCommand(); - cmd.CommandTimeout = 5; - cmd.CommandText = "select 1"; - return cmd; - } - public static bool Ping(this DbConnection that, bool isThrow = false) { - try { - PingCommand(that).ExecuteNonQuery(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - async public static Task PingAsync(this DbConnection that, bool isThrow = false) { - try { - await PingCommand(that).ExecuteNonQueryAsync(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - } + static DbCommand PingCommand(DbConnection conn) + { + var cmd = conn.CreateCommand(); + cmd.CommandTimeout = 5; + cmd.CommandText = "select 1"; + return cmd; + } + public static bool Ping(this DbConnection that, bool isThrow = false) + { + try + { + PingCommand(that).ExecuteNonQuery(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + async public static Task PingAsync(this DbConnection that, bool isThrow = false) + { + try + { + await PingCommand(that).ExecuteNonQueryAsync(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + } } diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLTypesConverter.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLTypesConverter.cs index cd0fc698..16e05bd0 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLTypesConverter.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLTypesConverter.cs @@ -7,134 +7,151 @@ using System.Linq; using System.Net; using System.Net.NetworkInformation; -namespace Newtonsoft.Json { - public class PostgreSQLTypesConverter : JsonConverter { - private static readonly Type typeof_BitArray = typeof(BitArray); +namespace Newtonsoft.Json +{ + public class PostgreSQLTypesConverter : JsonConverter + { + private static readonly Type typeof_BitArray = typeof(BitArray); - private static readonly Type typeof_NpgsqlPoint = typeof(NpgsqlPoint); - private static readonly Type typeof_NpgsqlLine = typeof(NpgsqlLine); - private static readonly Type typeof_NpgsqlLSeg = typeof(NpgsqlLSeg); - private static readonly Type typeof_NpgsqlBox = typeof(NpgsqlBox); - private static readonly Type typeof_NpgsqlPath = typeof(NpgsqlPath); - private static readonly Type typeof_NpgsqlPolygon = typeof(NpgsqlPolygon); - private static readonly Type typeof_NpgsqlCircle = typeof(NpgsqlCircle); + private static readonly Type typeof_NpgsqlPoint = typeof(NpgsqlPoint); + private static readonly Type typeof_NpgsqlLine = typeof(NpgsqlLine); + private static readonly Type typeof_NpgsqlLSeg = typeof(NpgsqlLSeg); + private static readonly Type typeof_NpgsqlBox = typeof(NpgsqlBox); + private static readonly Type typeof_NpgsqlPath = typeof(NpgsqlPath); + private static readonly Type typeof_NpgsqlPolygon = typeof(NpgsqlPolygon); + private static readonly Type typeof_NpgsqlCircle = typeof(NpgsqlCircle); - private static readonly Type typeof_Cidr = typeof((IPAddress, int)); - private static readonly Type typeof_IPAddress = typeof(IPAddress); - private static readonly Type typeof_PhysicalAddress = typeof(PhysicalAddress); + private static readonly Type typeof_Cidr = typeof((IPAddress, int)); + private static readonly Type typeof_IPAddress = typeof(IPAddress); + private static readonly Type typeof_PhysicalAddress = typeof(PhysicalAddress); - private static readonly Type typeof_String = typeof(string); + private static readonly Type typeof_String = typeof(string); - private static readonly Type typeof_NpgsqlRange_int = typeof(NpgsqlRange); - private static readonly Type typeof_NpgsqlRange_long = typeof(NpgsqlRange); - private static readonly Type typeof_NpgsqlRange_decimal = typeof(NpgsqlRange); - private static readonly Type typeof_NpgsqlRange_DateTime = typeof(NpgsqlRange); - public override bool CanConvert(Type objectType) { - Type ctype = objectType.IsArray ? objectType.GetElementType() : objectType; - var ctypeGenericType1 = ctype.GenericTypeArguments.FirstOrDefault(); + private static readonly Type typeof_NpgsqlRange_int = typeof(NpgsqlRange); + private static readonly Type typeof_NpgsqlRange_long = typeof(NpgsqlRange); + private static readonly Type typeof_NpgsqlRange_decimal = typeof(NpgsqlRange); + private static readonly Type typeof_NpgsqlRange_DateTime = typeof(NpgsqlRange); + public override bool CanConvert(Type objectType) + { + Type ctype = objectType.IsArray ? objectType.GetElementType() : objectType; + var ctypeGenericType1 = ctype.GenericTypeArguments.FirstOrDefault(); - if (ctype == typeof_BitArray) return true; + if (ctype == typeof_BitArray) return true; - if (ctype == typeof_NpgsqlPoint || ctypeGenericType1 == typeof_NpgsqlPoint) return true; - if (ctype == typeof_NpgsqlLine || ctypeGenericType1 == typeof_NpgsqlLine) return true; - if (ctype == typeof_NpgsqlLSeg || ctypeGenericType1 == typeof_NpgsqlLSeg) return true; - if (ctype == typeof_NpgsqlBox || ctypeGenericType1 == typeof_NpgsqlBox) return true; - if (ctype == typeof_NpgsqlPath || ctypeGenericType1 == typeof_NpgsqlPath) return true; - if (ctype == typeof_NpgsqlPolygon || ctypeGenericType1 == typeof_NpgsqlPolygon) return true; - if (ctype == typeof_NpgsqlCircle || ctypeGenericType1 == typeof_NpgsqlCircle) return true; + if (ctype == typeof_NpgsqlPoint || ctypeGenericType1 == typeof_NpgsqlPoint) return true; + if (ctype == typeof_NpgsqlLine || ctypeGenericType1 == typeof_NpgsqlLine) return true; + if (ctype == typeof_NpgsqlLSeg || ctypeGenericType1 == typeof_NpgsqlLSeg) return true; + if (ctype == typeof_NpgsqlBox || ctypeGenericType1 == typeof_NpgsqlBox) return true; + if (ctype == typeof_NpgsqlPath || ctypeGenericType1 == typeof_NpgsqlPath) return true; + if (ctype == typeof_NpgsqlPolygon || ctypeGenericType1 == typeof_NpgsqlPolygon) return true; + if (ctype == typeof_NpgsqlCircle || ctypeGenericType1 == typeof_NpgsqlCircle) return true; - if (ctype == typeof_Cidr || ctypeGenericType1 == typeof_Cidr) return true; - if (ctype == typeof_IPAddress) return true; - if (ctype == typeof_PhysicalAddress) return true; + if (ctype == typeof_Cidr || ctypeGenericType1 == typeof_Cidr) return true; + if (ctype == typeof_IPAddress) return true; + if (ctype == typeof_PhysicalAddress) return true; - if (ctype == typeof_NpgsqlRange_int || ctypeGenericType1 == typeof_NpgsqlRange_int) return true; - if (ctype == typeof_NpgsqlRange_long || ctypeGenericType1 == typeof_NpgsqlRange_long) return true; - if (ctype == typeof_NpgsqlRange_decimal || ctypeGenericType1 == typeof_NpgsqlRange_decimal) return true; - if (ctype == typeof_NpgsqlRange_DateTime || ctypeGenericType1 == typeof_NpgsqlRange_DateTime) return true; + if (ctype == typeof_NpgsqlRange_int || ctypeGenericType1 == typeof_NpgsqlRange_int) return true; + if (ctype == typeof_NpgsqlRange_long || ctypeGenericType1 == typeof_NpgsqlRange_long) return true; + if (ctype == typeof_NpgsqlRange_decimal || ctypeGenericType1 == typeof_NpgsqlRange_decimal) return true; + if (ctype == typeof_NpgsqlRange_DateTime || ctypeGenericType1 == typeof_NpgsqlRange_DateTime) return true; - return false; - } - private object YieldJToken(Type ctype, JToken jt, int rank) { - if (jt.Type == JTokenType.Null) return null; - if (rank == 0) { - var ctypeGenericType1 = ctype.GenericTypeArguments.FirstOrDefault();//ctype.Namespace == "System" && ctype.Name.StartsWith("Nullable`") ? ctype.GenericTypeArguments.FirstOrDefault() : null; - if (ctype == typeof_BitArray) return jt.ToString().ToBitArray(); + return false; + } + private object YieldJToken(Type ctype, JToken jt, int rank) + { + if (jt.Type == JTokenType.Null) return null; + if (rank == 0) + { + var ctypeGenericType1 = ctype.GenericTypeArguments.FirstOrDefault();//ctype.Namespace == "System" && ctype.Name.StartsWith("Nullable`") ? ctype.GenericTypeArguments.FirstOrDefault() : null; + if (ctype == typeof_BitArray) return jt.ToString().ToBitArray(); - if (ctype == typeof_NpgsqlPoint || ctypeGenericType1 == typeof_NpgsqlPoint) return NpgsqlPoint.Parse(jt.ToString()); - if (ctype == typeof_NpgsqlLine || ctypeGenericType1 == typeof_NpgsqlLine) return NpgsqlLine.Parse(jt.ToString()); - if (ctype == typeof_NpgsqlLSeg || ctypeGenericType1 == typeof_NpgsqlLSeg) return NpgsqlLSeg.Parse(jt.ToString()); - if (ctype == typeof_NpgsqlBox || ctypeGenericType1 == typeof_NpgsqlBox) return NpgsqlBox.Parse(jt.ToString()); - if (ctype == typeof_NpgsqlPath || ctypeGenericType1 == typeof_NpgsqlPath) return NpgsqlPath.Parse(jt.ToString()); - if (ctype == typeof_NpgsqlPolygon || ctypeGenericType1 == typeof_NpgsqlPolygon) return NpgsqlPolygon.Parse(jt.ToString()); - if (ctype == typeof_NpgsqlCircle || ctypeGenericType1 == typeof_NpgsqlCircle) return NpgsqlCircle.Parse(jt.ToString()); + if (ctype == typeof_NpgsqlPoint || ctypeGenericType1 == typeof_NpgsqlPoint) return NpgsqlPoint.Parse(jt.ToString()); + if (ctype == typeof_NpgsqlLine || ctypeGenericType1 == typeof_NpgsqlLine) return NpgsqlLine.Parse(jt.ToString()); + if (ctype == typeof_NpgsqlLSeg || ctypeGenericType1 == typeof_NpgsqlLSeg) return NpgsqlLSeg.Parse(jt.ToString()); + if (ctype == typeof_NpgsqlBox || ctypeGenericType1 == typeof_NpgsqlBox) return NpgsqlBox.Parse(jt.ToString()); + if (ctype == typeof_NpgsqlPath || ctypeGenericType1 == typeof_NpgsqlPath) return NpgsqlPath.Parse(jt.ToString()); + if (ctype == typeof_NpgsqlPolygon || ctypeGenericType1 == typeof_NpgsqlPolygon) return NpgsqlPolygon.Parse(jt.ToString()); + if (ctype == typeof_NpgsqlCircle || ctypeGenericType1 == typeof_NpgsqlCircle) return NpgsqlCircle.Parse(jt.ToString()); - if (ctype == typeof_Cidr || ctypeGenericType1 == typeof_Cidr) { - var cidrArgs = jt.ToString().Split(new[] { '/' }, 2); - return (IPAddress.Parse(cidrArgs.First()), cidrArgs.Length >= 2 ? int.TryParse(cidrArgs[1], out var tryCdirSubnet) ? tryCdirSubnet : 0 : 0); - } - if (ctype == typeof_IPAddress) return IPAddress.Parse(jt.ToString()); - if (ctype == typeof_PhysicalAddress) return PhysicalAddress.Parse(jt.ToString()); + if (ctype == typeof_Cidr || ctypeGenericType1 == typeof_Cidr) + { + var cidrArgs = jt.ToString().Split(new[] { '/' }, 2); + return (IPAddress.Parse(cidrArgs.First()), cidrArgs.Length >= 2 ? int.TryParse(cidrArgs[1], out var tryCdirSubnet) ? tryCdirSubnet : 0 : 0); + } + if (ctype == typeof_IPAddress) return IPAddress.Parse(jt.ToString()); + if (ctype == typeof_PhysicalAddress) return PhysicalAddress.Parse(jt.ToString()); - if (ctype == typeof_NpgsqlRange_int || ctypeGenericType1 == typeof_NpgsqlRange_int) return jt.ToString().ToNpgsqlRange(); - if (ctype == typeof_NpgsqlRange_long || ctypeGenericType1 == typeof_NpgsqlRange_long) return jt.ToString().ToNpgsqlRange(); - if (ctype == typeof_NpgsqlRange_decimal || ctypeGenericType1 == typeof_NpgsqlRange_decimal) return jt.ToString().ToNpgsqlRange(); - if (ctype == typeof_NpgsqlRange_DateTime || ctypeGenericType1 == typeof_NpgsqlRange_DateTime) return jt.ToString().ToNpgsqlRange(); + if (ctype == typeof_NpgsqlRange_int || ctypeGenericType1 == typeof_NpgsqlRange_int) return jt.ToString().ToNpgsqlRange(); + if (ctype == typeof_NpgsqlRange_long || ctypeGenericType1 == typeof_NpgsqlRange_long) return jt.ToString().ToNpgsqlRange(); + if (ctype == typeof_NpgsqlRange_decimal || ctypeGenericType1 == typeof_NpgsqlRange_decimal) return jt.ToString().ToNpgsqlRange(); + if (ctype == typeof_NpgsqlRange_DateTime || ctypeGenericType1 == typeof_NpgsqlRange_DateTime) return jt.ToString().ToNpgsqlRange(); - return null; - } - - var jtarr = jt.ToArray(); - var ret = Array.CreateInstance(ctype, jtarr.Length); - var jtarrIdx = 0; - foreach (var a in jtarr) { - var t2 = YieldJToken(ctype, a, rank - 1); - ret.SetValue(t2, jtarrIdx++); - } - return ret; - } - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { - int rank = objectType.IsArray ? objectType.GetArrayRank() : 0; - Type ctype = objectType.IsArray ? objectType.GetElementType() : objectType; + return null; + } - var ret = YieldJToken(ctype, JToken.Load(reader), rank); - if (ret != null && rank > 0) return ret; - return ret; - } - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - Type objectType = value.GetType(); - if (objectType.IsArray) { - int rank = objectType.GetArrayRank(); - int[] indices = new int[rank]; - GetJObject(value as Array, indices, 0).WriteTo(writer); - } else - GetJObject(value).WriteTo(writer); - } - public static JToken GetJObject(object value) { - if (value is BitArray) return JToken.FromObject((value as BitArray)?.To1010()); - if (value is IPAddress) return JToken.FromObject((value as IPAddress)?.ToString()); - if (value is ValueTuple || value is ValueTuple?) { - ValueTuple? cidrValue = (ValueTuple?)value; - return JToken.FromObject(cidrValue == null ? null : $"{cidrValue.Value.Item1.ToString()}/{cidrValue.Value.Item2.ToString()}"); - } - return JToken.FromObject(value?.ToString()); - } - public static JToken GetJObject(Array value, int[] indices, int idx) { - if (idx == indices.Length) { - return GetJObject(value.GetValue(indices)); - } - JArray ja = new JArray(); - if (indices.Length == 1) { - foreach(object a in value) - ja.Add(GetJObject(a)); - return ja; - } - int lb = value.GetLowerBound(idx); - int ub = value.GetUpperBound(idx); - for (int b = lb; b <= ub; b++) { - indices[idx] = b; - ja.Add(GetJObject(value, indices, idx + 1)); - } - return ja; - } - } + var jtarr = jt.ToArray(); + var ret = Array.CreateInstance(ctype, jtarr.Length); + var jtarrIdx = 0; + foreach (var a in jtarr) + { + var t2 = YieldJToken(ctype, a, rank - 1); + ret.SetValue(t2, jtarrIdx++); + } + return ret; + } + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + int rank = objectType.IsArray ? objectType.GetArrayRank() : 0; + Type ctype = objectType.IsArray ? objectType.GetElementType() : objectType; + + var ret = YieldJToken(ctype, JToken.Load(reader), rank); + if (ret != null && rank > 0) return ret; + return ret; + } + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + Type objectType = value.GetType(); + if (objectType.IsArray) + { + int rank = objectType.GetArrayRank(); + int[] indices = new int[rank]; + GetJObject(value as Array, indices, 0).WriteTo(writer); + } + else + GetJObject(value).WriteTo(writer); + } + public static JToken GetJObject(object value) + { + if (value is BitArray) return JToken.FromObject((value as BitArray)?.To1010()); + if (value is IPAddress) return JToken.FromObject((value as IPAddress)?.ToString()); + if (value is ValueTuple || value is ValueTuple?) + { + ValueTuple? cidrValue = (ValueTuple?)value; + return JToken.FromObject(cidrValue == null ? null : $"{cidrValue.Value.Item1.ToString()}/{cidrValue.Value.Item2.ToString()}"); + } + return JToken.FromObject(value?.ToString()); + } + public static JToken GetJObject(Array value, int[] indices, int idx) + { + if (idx == indices.Length) + { + return GetJObject(value.GetValue(indices)); + } + JArray ja = new JArray(); + if (indices.Length == 1) + { + foreach (object a in value) + ja.Add(GetJObject(a)); + return ja; + } + int lb = value.GetLowerBound(idx); + int ub = value.GetUpperBound(idx); + for (int b = lb; b <= ub; b++) + { + indices[idx] = b; + ja.Add(GetJObject(value, indices, idx + 1)); + } + return ja; + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLTypesExtensions.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLTypesExtensions.cs index 1eda91d1..ab1fb921 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLTypesExtensions.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLAdo/PostgreSQLTypesExtensions.cs @@ -3,63 +3,69 @@ using NpgsqlTypes; using System; using System.Collections; -public static partial class PostgreSQLTypesExtensions { - /// - /// 测量两个经纬度的距离,返回单位:米 - /// - /// 经纬坐标1 - /// 经纬坐标2 - /// 返回距离(单位:米) - public static double Distance(this NpgsqlPoint that, NpgsqlPoint point) { - double radLat1 = (double)(that.Y) * Math.PI / 180d; - double radLng1 = (double)(that.X) * Math.PI / 180d; - double radLat2 = (double)(point.Y) * Math.PI / 180d; - double radLng2 = (double)(point.X) * Math.PI / 180d; - return 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((radLat1 - radLat2) / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin((radLng1 - radLng2) / 2), 2))) * 6378137; - } +public static partial class PostgreSQLTypesExtensions +{ + /// + /// 测量两个经纬度的距离,返回单位:米 + /// + /// 经纬坐标1 + /// 经纬坐标2 + /// 返回距离(单位:米) + public static double Distance(this NpgsqlPoint that, NpgsqlPoint point) + { + double radLat1 = (double)(that.Y) * Math.PI / 180d; + double radLng1 = (double)(that.X) * Math.PI / 180d; + double radLat2 = (double)(point.Y) * Math.PI / 180d; + double radLng2 = (double)(point.X) * Math.PI / 180d; + return 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((radLat1 - radLat2) / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin((radLng1 - radLng2) / 2), 2))) * 6378137; + } - /// - /// 测量两个经纬度的距离,返回单位:米 - /// - /// 经纬坐标1 - /// 经纬坐标2 - /// 返回距离(单位:米) - public static double Distance(this PostgisPoint that, PostgisPoint point) { - double radLat1 = (double)(that.Y) * Math.PI / 180d; - double radLng1 = (double)(that.X) * Math.PI / 180d; - double radLat2 = (double)(point.Y) * Math.PI / 180d; - double radLng2 = (double)(point.X) * Math.PI / 180d; - return 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((radLat1 - radLat2) / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin((radLng1 - radLng2) / 2), 2))) * 6378137; - } + /// + /// 测量两个经纬度的距离,返回单位:米 + /// + /// 经纬坐标1 + /// 经纬坐标2 + /// 返回距离(单位:米) + public static double Distance(this PostgisPoint that, PostgisPoint point) + { + double radLat1 = (double)(that.Y) * Math.PI / 180d; + double radLng1 = (double)(that.X) * Math.PI / 180d; + double radLat2 = (double)(point.Y) * Math.PI / 180d; + double radLng2 = (double)(point.X) * Math.PI / 180d; + return 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((radLat1 - radLat2) / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin((radLng1 - radLng2) / 2), 2))) * 6378137; + } - public static string To1010(this BitArray ba) { - char[] ret = new char[ba.Length]; - for (int a = 0; a < ba.Length; a++) ret[a] = ba[a] ? '1' : '0'; - return new string(ret); - } + public static string To1010(this BitArray ba) + { + char[] ret = new char[ba.Length]; + for (int a = 0; a < ba.Length; a++) ret[a] = ba[a] ? '1' : '0'; + return new string(ret); + } - /// - /// 将 1010101010 这样的二进制字符串转换成 BitArray - /// - /// 1010101010 - /// - public static BitArray ToBitArray(this string _1010Str) { - if (_1010Str == null) return null; - BitArray ret = new BitArray(_1010Str.Length); - for (int a = 0; a < _1010Str.Length; a++) ret[a] = _1010Str[a] == '1'; - return ret; - } + /// + /// 将 1010101010 这样的二进制字符串转换成 BitArray + /// + /// 1010101010 + /// + public static BitArray ToBitArray(this string _1010Str) + { + if (_1010Str == null) return null; + BitArray ret = new BitArray(_1010Str.Length); + for (int a = 0; a < _1010Str.Length; a++) ret[a] = _1010Str[a] == '1'; + return ret; + } - public static NpgsqlRange ToNpgsqlRange(this string that) { - var s = that; - if (string.IsNullOrEmpty(s) || s == "empty") return NpgsqlRange.Empty; - string s1 = s.Trim('(', ')', '[', ']'); - string[] ss = s1.Split(new char[] { ',' }, 2); - if (ss.Length != 2) return NpgsqlRange.Empty; - T t1 = default(T); - T t2 = default(T); - if (!string.IsNullOrEmpty(ss[0])) t1 = (T)Convert.ChangeType(ss[0], typeof(T)); - if (!string.IsNullOrEmpty(ss[1])) t2 = (T)Convert.ChangeType(ss[1], typeof(T)); - return new NpgsqlRange(t1, s[0] == '[', s[0] == '(', t2, s[s.Length - 1] == ']', s[s.Length - 1] == ')'); - } + public static NpgsqlRange ToNpgsqlRange(this string that) + { + var s = that; + if (string.IsNullOrEmpty(s) || s == "empty") return NpgsqlRange.Empty; + string s1 = s.Trim('(', ')', '[', ']'); + string[] ss = s1.Split(new char[] { ',' }, 2); + if (ss.Length != 2) return NpgsqlRange.Empty; + T t1 = default(T); + T t2 = default(T); + if (!string.IsNullOrEmpty(ss[0])) t1 = (T)Convert.ChangeType(ss[0], typeof(T)); + if (!string.IsNullOrEmpty(ss[1])) t2 = (T)Convert.ChangeType(ss[1], typeof(T)); + return new NpgsqlRange(t1, s[0] == '[', s[0] == '(', t2, s[s.Length - 1] == ']', s[s.Length - 1] == ')'); + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLCodeFirst.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLCodeFirst.cs index 708f73a3..78742220 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLCodeFirst.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLCodeFirst.cs @@ -16,164 +16,182 @@ using System.Net.NetworkInformation; using System.Text; using System.Text.RegularExpressions; -namespace FreeSql.PostgreSQL { +namespace FreeSql.PostgreSQL +{ - class PostgreSQLCodeFirst : Internal.CommonProvider.CodeFirstProvider { + class PostgreSQLCodeFirst : Internal.CommonProvider.CodeFirstProvider + { - public PostgreSQLCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } + public PostgreSQLCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } - static object _dicCsToDbLock = new object(); - static Dictionary _dicCsToDb = new Dictionary() { + static object _dicCsToDbLock = new object(); + static Dictionary _dicCsToDb = new Dictionary() { - { typeof(sbyte).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) }, - { typeof(short).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(short?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) }, - { typeof(int).FullName, (NpgsqlDbType.Integer, "int4","int4 NOT NULL", false, false, 0) },{ typeof(int?).FullName, (NpgsqlDbType.Integer, "int4", "int4", false, true, null) }, - { typeof(long).FullName, (NpgsqlDbType.Bigint, "int8","int8 NOT NULL", false, false, 0) },{ typeof(long?).FullName, (NpgsqlDbType.Bigint, "int8", "int8", false, true, null) }, + { typeof(sbyte).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) }, + { typeof(short).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(short?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) }, + { typeof(int).FullName, (NpgsqlDbType.Integer, "int4","int4 NOT NULL", false, false, 0) },{ typeof(int?).FullName, (NpgsqlDbType.Integer, "int4", "int4", false, true, null) }, + { typeof(long).FullName, (NpgsqlDbType.Bigint, "int8","int8 NOT NULL", false, false, 0) },{ typeof(long?).FullName, (NpgsqlDbType.Bigint, "int8", "int8", false, true, null) }, - { typeof(byte).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(byte?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) }, - { typeof(ushort).FullName, (NpgsqlDbType.Integer, "int4","int4 NOT NULL", false, false, 0) },{ typeof(ushort?).FullName, (NpgsqlDbType.Integer, "int4", "int4", false, true, null) }, - { typeof(uint).FullName, (NpgsqlDbType.Bigint, "int8","int8 NOT NULL", false, false, 0) },{ typeof(uint?).FullName, (NpgsqlDbType.Bigint, "int8", "int8", false, true, null) }, - { typeof(ulong).FullName, (NpgsqlDbType.Numeric, "numeric","numeric(20,0) NOT NULL", false, false, 0) },{ typeof(ulong?).FullName, (NpgsqlDbType.Numeric, "numeric", "numeric(20,0)", false, true, null) }, + { typeof(byte).FullName, (NpgsqlDbType.Smallint, "int2","int2 NOT NULL", false, false, 0) },{ typeof(byte?).FullName, (NpgsqlDbType.Smallint, "int2", "int2", false, true, null) }, + { typeof(ushort).FullName, (NpgsqlDbType.Integer, "int4","int4 NOT NULL", false, false, 0) },{ typeof(ushort?).FullName, (NpgsqlDbType.Integer, "int4", "int4", false, true, null) }, + { typeof(uint).FullName, (NpgsqlDbType.Bigint, "int8","int8 NOT NULL", false, false, 0) },{ typeof(uint?).FullName, (NpgsqlDbType.Bigint, "int8", "int8", false, true, null) }, + { typeof(ulong).FullName, (NpgsqlDbType.Numeric, "numeric","numeric(20,0) NOT NULL", false, false, 0) },{ typeof(ulong?).FullName, (NpgsqlDbType.Numeric, "numeric", "numeric(20,0)", false, true, null) }, - { typeof(float).FullName, (NpgsqlDbType.Real, "float4","float4 NOT NULL", false, false, 0) },{ typeof(float?).FullName, (NpgsqlDbType.Real, "float4", "float4", false, true, null) }, - { typeof(double).FullName, (NpgsqlDbType.Double, "float8","float8 NOT NULL", false, false, 0) },{ typeof(double?).FullName, (NpgsqlDbType.Double, "float8", "float8", false, true, null) }, - { typeof(decimal).FullName, (NpgsqlDbType.Numeric, "numeric", "numeric(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (NpgsqlDbType.Numeric, "numeric", "numeric(10,2)", false, true, null) }, + { typeof(float).FullName, (NpgsqlDbType.Real, "float4","float4 NOT NULL", false, false, 0) },{ typeof(float?).FullName, (NpgsqlDbType.Real, "float4", "float4", false, true, null) }, + { typeof(double).FullName, (NpgsqlDbType.Double, "float8","float8 NOT NULL", false, false, 0) },{ typeof(double?).FullName, (NpgsqlDbType.Double, "float8", "float8", false, true, null) }, + { typeof(decimal).FullName, (NpgsqlDbType.Numeric, "numeric", "numeric(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (NpgsqlDbType.Numeric, "numeric", "numeric(10,2)", false, true, null) }, - { typeof(string).FullName, (NpgsqlDbType.Varchar, "varchar", "varchar(255)", false, null, "") }, + { typeof(string).FullName, (NpgsqlDbType.Varchar, "varchar", "varchar(255)", false, null, "") }, - { typeof(TimeSpan).FullName, (NpgsqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (NpgsqlDbType.Time, "time", "time",false, true, null) }, - { typeof(DateTime).FullName, (NpgsqlDbType.Timestamp, "timestamp", "timestamp NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (NpgsqlDbType.Timestamp, "timestamp", "timestamp", false, true, null) }, + { typeof(TimeSpan).FullName, (NpgsqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (NpgsqlDbType.Time, "time", "time",false, true, null) }, + { typeof(DateTime).FullName, (NpgsqlDbType.Timestamp, "timestamp", "timestamp NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (NpgsqlDbType.Timestamp, "timestamp", "timestamp", false, true, null) }, - { typeof(bool).FullName, (NpgsqlDbType.Boolean, "bool","bool NOT NULL", null, false, false) },{ typeof(bool?).FullName, (NpgsqlDbType.Boolean, "bool","bool", null, true, null) }, - { typeof(Byte[]).FullName, (NpgsqlDbType.Bytea, "bytea", "bytea", false, null, new byte[0]) }, - { typeof(BitArray).FullName, (NpgsqlDbType.Varbit, "varbit", "varbit(64)", false, null, new BitArray(new byte[64])) }, + { typeof(bool).FullName, (NpgsqlDbType.Boolean, "bool","bool NOT NULL", null, false, false) },{ typeof(bool?).FullName, (NpgsqlDbType.Boolean, "bool","bool", null, true, null) }, + { typeof(Byte[]).FullName, (NpgsqlDbType.Bytea, "bytea", "bytea", false, null, new byte[0]) }, + { typeof(BitArray).FullName, (NpgsqlDbType.Varbit, "varbit", "varbit(64)", false, null, new BitArray(new byte[64])) }, - { typeof(NpgsqlPoint).FullName, (NpgsqlDbType.Point, "point", "point NOT NULL", false, false, new NpgsqlPoint(0, 0)) },{ typeof(NpgsqlPoint?).FullName, (NpgsqlDbType.Point, "point", "point", false, true, null) }, - { typeof(NpgsqlLine).FullName, (NpgsqlDbType.Line, "line", "line NOT NULL", false, false, new NpgsqlLine(0, 0, 1)) },{ typeof(NpgsqlLine?).FullName, (NpgsqlDbType.Line, "line", "line", false, true, null) }, - { typeof(NpgsqlLSeg).FullName, (NpgsqlDbType.LSeg, "lseg", "lseg NOT NULL", false, false, new NpgsqlLSeg(0, 0, 0, 0)) },{ typeof(NpgsqlLSeg?).FullName, (NpgsqlDbType.LSeg, "lseg", "lseg", false, true, null) }, - { typeof(NpgsqlBox).FullName, (NpgsqlDbType.Box, "box", "box NOT NULL", false, false, new NpgsqlBox(0, 0, 0, 0)) },{ typeof(NpgsqlBox?).FullName, (NpgsqlDbType.Box, "box", "box", false, true, null) }, - { typeof(NpgsqlPath).FullName, (NpgsqlDbType.Path, "path", "path NOT NULL", false, false, new NpgsqlPath(new NpgsqlPoint(0, 0))) },{ typeof(NpgsqlPath?).FullName, (NpgsqlDbType.Path, "path", "path", false, true, null) }, - { typeof(NpgsqlPolygon).FullName, (NpgsqlDbType.Polygon, "polygon", "polygon NOT NULL", false, false, new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0))) },{ typeof(NpgsqlPolygon?).FullName, (NpgsqlDbType.Polygon, "polygon", "polygon", false, true, null) }, - { typeof(NpgsqlCircle).FullName, (NpgsqlDbType.Circle, "circle", "circle NOT NULL", false, false, new NpgsqlCircle(0, 0, 0)) },{ typeof(NpgsqlCircle?).FullName, (NpgsqlDbType.Circle, "circle", "circle", false, true, null) }, + { typeof(NpgsqlPoint).FullName, (NpgsqlDbType.Point, "point", "point NOT NULL", false, false, new NpgsqlPoint(0, 0)) },{ typeof(NpgsqlPoint?).FullName, (NpgsqlDbType.Point, "point", "point", false, true, null) }, + { typeof(NpgsqlLine).FullName, (NpgsqlDbType.Line, "line", "line NOT NULL", false, false, new NpgsqlLine(0, 0, 1)) },{ typeof(NpgsqlLine?).FullName, (NpgsqlDbType.Line, "line", "line", false, true, null) }, + { typeof(NpgsqlLSeg).FullName, (NpgsqlDbType.LSeg, "lseg", "lseg NOT NULL", false, false, new NpgsqlLSeg(0, 0, 0, 0)) },{ typeof(NpgsqlLSeg?).FullName, (NpgsqlDbType.LSeg, "lseg", "lseg", false, true, null) }, + { typeof(NpgsqlBox).FullName, (NpgsqlDbType.Box, "box", "box NOT NULL", false, false, new NpgsqlBox(0, 0, 0, 0)) },{ typeof(NpgsqlBox?).FullName, (NpgsqlDbType.Box, "box", "box", false, true, null) }, + { typeof(NpgsqlPath).FullName, (NpgsqlDbType.Path, "path", "path NOT NULL", false, false, new NpgsqlPath(new NpgsqlPoint(0, 0))) },{ typeof(NpgsqlPath?).FullName, (NpgsqlDbType.Path, "path", "path", false, true, null) }, + { typeof(NpgsqlPolygon).FullName, (NpgsqlDbType.Polygon, "polygon", "polygon NOT NULL", false, false, new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0))) },{ typeof(NpgsqlPolygon?).FullName, (NpgsqlDbType.Polygon, "polygon", "polygon", false, true, null) }, + { typeof(NpgsqlCircle).FullName, (NpgsqlDbType.Circle, "circle", "circle NOT NULL", false, false, new NpgsqlCircle(0, 0, 0)) },{ typeof(NpgsqlCircle?).FullName, (NpgsqlDbType.Circle, "circle", "circle", false, true, null) }, - { typeof((IPAddress Address, int Subnet)).FullName, (NpgsqlDbType.Cidr, "cidr", "cidr NOT NULL", false, false, (IPAddress.Any, 0)) },{ typeof((IPAddress Address, int Subnet)?).FullName, (NpgsqlDbType.Cidr, "cidr", "cidr", false, true, null) }, - { typeof(IPAddress).FullName, (NpgsqlDbType.Inet, "inet", "inet", false, null, IPAddress.Any) }, - { typeof(PhysicalAddress).FullName, (NpgsqlDbType.MacAddr, "macaddr", "macaddr", false, null, PhysicalAddress.None) }, + { typeof((IPAddress Address, int Subnet)).FullName, (NpgsqlDbType.Cidr, "cidr", "cidr NOT NULL", false, false, (IPAddress.Any, 0)) },{ typeof((IPAddress Address, int Subnet)?).FullName, (NpgsqlDbType.Cidr, "cidr", "cidr", false, true, null) }, + { typeof(IPAddress).FullName, (NpgsqlDbType.Inet, "inet", "inet", false, null, IPAddress.Any) }, + { typeof(PhysicalAddress).FullName, (NpgsqlDbType.MacAddr, "macaddr", "macaddr", false, null, PhysicalAddress.None) }, - { typeof(JToken).FullName, (NpgsqlDbType.Jsonb, "jsonb", "jsonb", false, null, JToken.Parse("{}")) }, - { typeof(JObject).FullName, (NpgsqlDbType.Jsonb, "jsonb", "jsonb", false, null, JObject.Parse("{}")) }, - { typeof(JArray).FullName, (NpgsqlDbType.Jsonb, "jsonb", "jsonb", false, null, JArray.Parse("[]")) }, - { typeof(Guid).FullName, (NpgsqlDbType.Uuid, "uuid", "uuid NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (NpgsqlDbType.Uuid, "uuid", "uuid", false, true, null) }, + { typeof(JToken).FullName, (NpgsqlDbType.Jsonb, "jsonb", "jsonb", false, null, JToken.Parse("{}")) }, + { typeof(JObject).FullName, (NpgsqlDbType.Jsonb, "jsonb", "jsonb", false, null, JObject.Parse("{}")) }, + { typeof(JArray).FullName, (NpgsqlDbType.Jsonb, "jsonb", "jsonb", false, null, JArray.Parse("[]")) }, + { typeof(Guid).FullName, (NpgsqlDbType.Uuid, "uuid", "uuid NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (NpgsqlDbType.Uuid, "uuid", "uuid", false, true, null) }, - { typeof(NpgsqlRange).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Integer, "int4range", "int4range NOT NULL", false, false, NpgsqlRange.Empty) },{ typeof(NpgsqlRange?).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Integer, "int4range", "int4range", false, true, null) }, - { typeof(NpgsqlRange).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Bigint, "int8range", "int8range NOT NULL", false, false, NpgsqlRange.Empty) },{ typeof(NpgsqlRange?).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Bigint, "int8range", "int8range", false, true, null) }, - { typeof(NpgsqlRange).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Numeric, "numrange", "numrange NOT NULL", false, false, NpgsqlRange.Empty) },{ typeof(NpgsqlRange?).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Numeric, "numrange", "numrange", false, true, null) }, - { typeof(NpgsqlRange).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Timestamp, "tsrange", "tsrange NOT NULL", false, false, NpgsqlRange.Empty) },{ typeof(NpgsqlRange?).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Timestamp, "tsrange", "tsrange", false, true, null) }, + { typeof(NpgsqlRange).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Integer, "int4range", "int4range NOT NULL", false, false, NpgsqlRange.Empty) },{ typeof(NpgsqlRange?).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Integer, "int4range", "int4range", false, true, null) }, + { typeof(NpgsqlRange).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Bigint, "int8range", "int8range NOT NULL", false, false, NpgsqlRange.Empty) },{ typeof(NpgsqlRange?).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Bigint, "int8range", "int8range", false, true, null) }, + { typeof(NpgsqlRange).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Numeric, "numrange", "numrange NOT NULL", false, false, NpgsqlRange.Empty) },{ typeof(NpgsqlRange?).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Numeric, "numrange", "numrange", false, true, null) }, + { typeof(NpgsqlRange).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Timestamp, "tsrange", "tsrange NOT NULL", false, false, NpgsqlRange.Empty) },{ typeof(NpgsqlRange?).FullName, (NpgsqlDbType.Range | NpgsqlDbType.Timestamp, "tsrange", "tsrange", false, true, null) }, - { typeof(Dictionary).FullName, (NpgsqlDbType.Hstore, "hstore", "hstore", false, null, new Dictionary()) }, - { typeof(PostgisPoint).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisPoint(0, 0)) }, - { typeof(PostgisLineString).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisLineString(new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) })) }, - { typeof(PostgisPolygon).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisPolygon(new []{new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }, new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) } })) }, - { typeof(PostgisMultiPoint).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisMultiPoint(new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) })) }, - { typeof(PostgisMultiLineString).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisMultiLineString(new[]{new PostgisLineString(new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }),new PostgisLineString(new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }) })) }, - { typeof(PostgisMultiPolygon).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisMultiPolygon(new[]{new PostgisPolygon(new []{new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }, new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) } }),new PostgisPolygon(new []{new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }, new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) } }) })) }, - { typeof(PostgisGeometry).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisPoint(0, 0)) }, - { typeof(PostgisGeometryCollection).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisGeometryCollection(new[]{new PostgisPoint(0, 0),new PostgisPoint(0, 0) })) }, - }; + { typeof(Dictionary).FullName, (NpgsqlDbType.Hstore, "hstore", "hstore", false, null, new Dictionary()) }, + { typeof(PostgisPoint).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisPoint(0, 0)) }, + { typeof(PostgisLineString).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisLineString(new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) })) }, + { typeof(PostgisPolygon).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisPolygon(new []{new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }, new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) } })) }, + { typeof(PostgisMultiPoint).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisMultiPoint(new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) })) }, + { typeof(PostgisMultiLineString).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisMultiLineString(new[]{new PostgisLineString(new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }),new PostgisLineString(new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }) })) }, + { typeof(PostgisMultiPolygon).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisMultiPolygon(new[]{new PostgisPolygon(new []{new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }, new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) } }),new PostgisPolygon(new []{new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) }, new []{new Coordinate2D(0, 0),new Coordinate2D(0, 0) } }) })) }, + { typeof(PostgisGeometry).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisPoint(0, 0)) }, + { typeof(PostgisGeometryCollection).FullName, (NpgsqlDbType.Geometry, "geometry", "geometry", false, null, new PostgisGeometryCollection(new[]{new PostgisPoint(0, 0),new PostgisPoint(0, 0) })) }, + }; - public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) { - var isarray = type.FullName != "System.Byte[]" && type.IsArray; - var elementType = isarray ? type.GetElementType() : type; - var info = GetDbInfoNoneArray(elementType); - if (info == null) return null; - if (isarray == false) return ((int)info.Value.type, info.Value.dbtype, info.Value.dbtypeFull, info.Value.isnullable, info.Value.defaultValue); - var dbtypefull = Regex.Replace(info.Value.dbtypeFull, $@"{info.Value.dbtype}(\s*\([^\)]+\))?", "$0[]").Replace(" NOT NULL", ""); - return ((int)(info.Value.type | NpgsqlDbType.Array), $"{info.Value.dbtype}[]", dbtypefull, null, Array.CreateInstance(elementType, 0)); - } - (NpgsqlDbType type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfoNoneArray(Type type) { - if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (NpgsqlDbType, string, string, bool?, object)?((trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); - if (type.IsArray) return null; - var enumType = type.IsEnum ? type : null; - if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); - if (enumType != null) { - var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? - (NpgsqlDbType.Bigint, "int8", $"int8{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : - (NpgsqlDbType.Integer, "int4", $"int4{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); - if (_dicCsToDb.ContainsKey(type.FullName) == false) { - lock (_dicCsToDbLock) { - if (_dicCsToDb.ContainsKey(type.FullName) == false) - _dicCsToDb.Add(type.FullName, newItem); - } - } - return (newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); - } - return null; - } - - public override string GetComparisonDDLStatements(params Type[] entityTypes) { - var sb = new StringBuilder(); - var seqcols = new List<(ColumnInfo, string[], bool)>(); //序列 + public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) + { + var isarray = type.FullName != "System.Byte[]" && type.IsArray; + var elementType = isarray ? type.GetElementType() : type; + var info = GetDbInfoNoneArray(elementType); + if (info == null) return null; + if (isarray == false) return ((int)info.Value.type, info.Value.dbtype, info.Value.dbtypeFull, info.Value.isnullable, info.Value.defaultValue); + var dbtypefull = Regex.Replace(info.Value.dbtypeFull, $@"{info.Value.dbtype}(\s*\([^\)]+\))?", "$0[]").Replace(" NOT NULL", ""); + return ((int)(info.Value.type | NpgsqlDbType.Array), $"{info.Value.dbtype}[]", dbtypefull, null, Array.CreateInstance(elementType, 0)); + } + (NpgsqlDbType type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfoNoneArray(Type type) + { + if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (NpgsqlDbType, string, string, bool?, object)?((trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); + if (type.IsArray) return null; + var enumType = type.IsEnum ? type : null; + if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); + if (enumType != null) + { + var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? + (NpgsqlDbType.Bigint, "int8", $"int8{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : + (NpgsqlDbType.Integer, "int4", $"int4{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); + if (_dicCsToDb.ContainsKey(type.FullName) == false) + { + lock (_dicCsToDbLock) + { + if (_dicCsToDb.ContainsKey(type.FullName) == false) + _dicCsToDb.Add(type.FullName, newItem); + } + } + return (newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); + } + return null; + } - foreach (var entityType in entityTypes) { - if (sb.Length > 0) sb.Append("\r\n"); - var tb = _commonUtils.GetTableByEntity(entityType); - if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); - if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); - var tbname = tb.DbName.Split(new[] { '.' }, 2); - if (tbname?.Length == 1) tbname = new[] { "public", tbname[0] }; + public override string GetComparisonDDLStatements(params Type[] entityTypes) + { + var sb = new StringBuilder(); + var seqcols = new List<(ColumnInfo, string[], bool)>(); //序列 - var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名 - if (tboldname?.Length == 1) tboldname = new[] { "public", tboldname[0] }; + foreach (var entityType in entityTypes) + { + if (sb.Length > 0) sb.Append("\r\n"); + var tb = _commonUtils.GetTableByEntity(entityType); + if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); + if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); + var tbname = tb.DbName.Split(new[] { '.' }, 2); + if (tbname?.Length == 1) tbname = new[] { "public", tbname[0] }; - if (string.Compare(tbname[0], "public", true) != 0 && _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from pg_namespace where nspname={0}", tbname[0])) == null) //创建模式 - sb.Append("CREATE SCHEMA IF NOT EXISTS ").Append(tbname[0]).Append(";\r\n"); + var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名 + if (tboldname?.Length == 1) tboldname = new[] { "public", tboldname[0] }; - var sbalter = new StringBuilder(); - var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 - if (_orm.Ado.ExecuteScalar(CommandType.Text, string.Format(" select 1 from pg_tables a inner join pg_namespace b on b.nspname = a.schemaname where b.nspname || '.' || a.tablename = '{0}.{1}'", tbname)) == null) { //表不存在 - if (tboldname != null) { - if (_orm.Ado.ExecuteScalar(CommandType.Text, string.Format(" select 1 from pg_tables a inner join pg_namespace b on b.nspname = a.schemaname where b.nspname || '.' || a.tablename = '{0}.{1}'", tboldname)) == null) - //旧表不存在 - tboldname = null; - } - if (tboldname == null) { - //创建表 - sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( "); - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(","); - if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, true)); - } - if (tb.Primarys.Any()) { - sb.Append(" \r\n CONSTRAINT ").Append(tbname[0]).Append("_").Append(tbname[1]).Append("_pkey PRIMARY KEY ("); - foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1); - sb.Append("\r\n) WITH (OIDS=FALSE);\r\n"); - //备注 - foreach (var tbcol in tb.Columns.Values) { - if (string.IsNullOrEmpty(tbcol.Comment) == false) - sb.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); - } - continue; - } - //如果新表,旧表在一个数据库和模式下,直接修改表名 - if (string.Compare(tbname[0], tboldname[0], true) == 0) - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}")).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append(";\r\n"); - else { - //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 - istmpatler = true; - } - } else - tboldname = null; //如果新表已经存在,不走改表名逻辑 + if (string.Compare(tbname[0], "public", true) != 0 && _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(" select 1 from pg_namespace where nspname={0}", tbname[0])) == null) //创建模式 + sb.Append("CREATE SCHEMA IF NOT EXISTS ").Append(tbname[0]).Append(";\r\n"); - //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 - var sql = _commonUtils.FormatSql(@" + var sbalter = new StringBuilder(); + var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 + if (_orm.Ado.ExecuteScalar(CommandType.Text, string.Format(" select 1 from pg_tables a inner join pg_namespace b on b.nspname = a.schemaname where b.nspname || '.' || a.tablename = '{0}.{1}'", tbname)) == null) + { //表不存在 + if (tboldname != null) + { + if (_orm.Ado.ExecuteScalar(CommandType.Text, string.Format(" select 1 from pg_tables a inner join pg_namespace b on b.nspname = a.schemaname where b.nspname || '.' || a.tablename = '{0}.{1}'", tboldname)) == null) + //旧表不存在 + tboldname = null; + } + if (tboldname == null) + { + //创建表 + sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( "); + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(","); + if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, true)); + } + if (tb.Primarys.Any()) + { + sb.Append(" \r\n CONSTRAINT ").Append(tbname[0]).Append("_").Append(tbname[1]).Append("_pkey PRIMARY KEY ("); + foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1); + sb.Append("\r\n) WITH (OIDS=FALSE);\r\n"); + //备注 + foreach (var tbcol in tb.Columns.Values) + { + if (string.IsNullOrEmpty(tbcol.Comment) == false) + sb.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); + } + continue; + } + //如果新表,旧表在一个数据库和模式下,直接修改表名 + if (string.Compare(tbname[0], tboldname[0], true) == 0) + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}")).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append(";\r\n"); + else + { + //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 + istmpatler = true; + } + } + else + tboldname = null; //如果新表已经存在,不走改表名逻辑 + + //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 + var sql = _commonUtils.FormatSql(@" select a.attname, t.typname, @@ -192,59 +210,66 @@ left join pg_attrdef e on e.adrelid = a.attrelid and e.adnum = a.attnum inner join pg_namespace ns on ns.oid = c.relnamespace inner join pg_namespace ns2 on ns2.oid = t.typnamespace where ns.nspname = {0} and c.relname = {1}", tboldname ?? tbname); - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => { - var attndims = int.Parse(string.Concat(a[6])); - var type = string.Concat(a[1]); - var sqlType = string.Concat(a[3]); - var max_length = long.Parse(string.Concat(a[2])); - switch (sqlType.ToLower()) { - case "bool": case "name": case "bit": case "varbit": case "bpchar": case "varchar": case "bytea": case "text": case "uuid": break; - default: max_length *= 8; break; - } - if (type.StartsWith("_")) { - type = type.Substring(1); - if (attndims == 0) attndims++; - } - if (sqlType.StartsWith("_")) sqlType = sqlType.Substring(1); - return new { - column = string.Concat(a[0]), - sqlType = string.Concat(sqlType), - max_length = long.Parse(string.Concat(a[2])), - is_nullable = string.Concat(a[4]) == "1", - is_identity = string.Concat(a[5]).StartsWith(@"nextval('") && string.Concat(a[5]).EndsWith(@"'::regclass)"), - attndims, - comment = string.Concat(a[7]) - }; - }, StringComparer.CurrentCultureIgnoreCase); + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => + { + var attndims = int.Parse(string.Concat(a[6])); + var type = string.Concat(a[1]); + var sqlType = string.Concat(a[3]); + var max_length = long.Parse(string.Concat(a[2])); + switch (sqlType.ToLower()) + { + case "bool": case "name": case "bit": case "varbit": case "bpchar": case "varchar": case "bytea": case "text": case "uuid": break; + default: max_length *= 8; break; + } + if (type.StartsWith("_")) + { + type = type.Substring(1); + if (attndims == 0) attndims++; + } + if (sqlType.StartsWith("_")) sqlType = sqlType.Substring(1); + return new + { + column = string.Concat(a[0]), + sqlType = string.Concat(sqlType), + max_length = long.Parse(string.Concat(a[2])), + is_nullable = string.Concat(a[4]) == "1", + is_identity = string.Concat(a[5]).StartsWith(@"nextval('") && string.Concat(a[5]).EndsWith(@"'::regclass)"), + attndims, + comment = string.Concat(a[7]) + }; + }, StringComparer.CurrentCultureIgnoreCase); - if (istmpatler == false) { - foreach (var tbcol in tb.Columns.Values) { - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? ""); - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false || - tbcol.Attribute.DbType.Contains("[]") != (tbstructcol.attndims > 0)) - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" TYPE ").Append(tbcol.Attribute.DbType.Split(' ').First()).Append(";\r\n"); - if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.IsNullable == true ? "DROP" : "SET").Append(" NOT NULL;\r\n"); - if (tbcol.Attribute.IsIdentity != tbstructcol.is_identity) - seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); - if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) - //修改列名 - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" RENAME COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" TO ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(";\r\n"); - if (isCommentChanged) - sbalter.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); - continue; - } - //添加列 - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD COLUMN ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType.Split(' ').First()).Append(";\r\n"); - sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(_commonUtils.FormatSql("{0};\r\n", tbcol.Attribute.DbDefautValue)); - if (tbcol.Attribute.IsNullable == false) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" SET NOT NULL;\r\n"); - if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); - if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); - } - var dsuksql = _commonUtils.FormatSql(@" + if (istmpatler == false) + { + foreach (var tbcol in tb.Columns.Values) + { + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? ""); + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false || + tbcol.Attribute.DbType.Contains("[]") != (tbstructcol.attndims > 0)) + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" TYPE ").Append(tbcol.Attribute.DbType.Split(' ').First()).Append(";\r\n"); + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" ").Append(tbcol.Attribute.IsNullable == true ? "DROP" : "SET").Append(" NOT NULL;\r\n"); + if (tbcol.Attribute.IsIdentity != tbstructcol.is_identity) + seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); + if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) + //修改列名 + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" RENAME COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" TO ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(";\r\n"); + if (isCommentChanged) + sbalter.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); + continue; + } + //添加列 + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD COLUMN ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType.Split(' ').First()).Append(";\r\n"); + sbalter.Append("UPDATE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" = ").Append(_commonUtils.FormatSql("{0};\r\n", tbcol.Attribute.DbDefautValue)); + if (tbcol.Attribute.IsNullable == false) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" SET NOT NULL;\r\n"); + if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true)); + if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); + } + var dsuksql = _commonUtils.FormatSql(@" select c.attname, b.relname @@ -254,91 +279,103 @@ inner join pg_attribute c on c.attnum > 0 and c.attrelid = b.oid inner join pg_namespace ns on ns.oid = b.relnamespace inner join pg_class d on d.oid = a.indrelid where ns.nspname in ({0}) and d.relname in ({1}) and a.indisunique = 't'", tboldname ?? tbname); - var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) }); - foreach (var uk in tb.Uniques) { - if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; - var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); - if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) { - if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n"); - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n"); - } - } - } - if (istmpatler == false) { - sb.Append(sbalter); - continue; - } - var oldpk = _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(@"select pg_constraint.conname as pk_name from pg_constraint + var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) }); + foreach (var uk in tb.Uniques) + { + if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; + var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); + if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) + { + if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n"); + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n"); + } + } + } + if (istmpatler == false) + { + sb.Append(sbalter); + continue; + } + var oldpk = _orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(@"select pg_constraint.conname as pk_name from pg_constraint inner join pg_class on pg_constraint.conrelid = pg_class.oid inner join pg_namespace on pg_namespace.oid = pg_class.relnamespace where pg_namespace.nspname={0} and pg_class.relname={1} and pg_constraint.contype='p' ", tbname))?.ToString(); - if (string.IsNullOrEmpty(oldpk) == false) - sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(oldpk).Append(";\r\n"); + if (string.IsNullOrEmpty(oldpk) == false) + sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(oldpk).Append(";\r\n"); - //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 - var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"); - var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.FreeSqlTmp_{tbname[1]}"); - //创建临时表 - sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(","); - if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, true)); - } - if (tb.Primarys.Any()) { - sb.Append(" \r\n CONSTRAINT ").Append(tbname[0]).Append("_").Append(tbname[1]).Append("_pkey PRIMARY KEY ("); - foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1); - sb.Append("\r\n) WITH (OIDS=FALSE);\r\n"); - //备注 - foreach (var tbcol in tb.Columns.Values) { - if (string.IsNullOrEmpty(tbcol.Comment) == false) - sb.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.FreeSqlTmp_{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); - } - sb.Append("INSERT INTO ").Append(tmptablename).Append(" ("); - foreach (var tbcol in tb.Columns.Values) - sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append(")\r\nSELECT "); - foreach (var tbcol in tb.Columns.Values) { - var insertvalue = "NULL"; - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) - insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; - if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"coalesce({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; - } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); - sb.Append(insertvalue).Append(", "); - } - sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); - sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n"); - sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName(tbname[1])).Append(";\r\n"); - } - foreach (var seqcol in seqcols) { - var tbname = seqcol.Item2; - var seqname = Utils.GetCsName($"{tbname[0]}.{tbname[1]}_{seqcol.Item1.Attribute.Name}_sequence_name"); - var tbname2 = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}"); - var colname2 = _commonUtils.QuoteSqlName(seqcol.Item1.Attribute.Name); - sb.Append("ALTER TABLE ").Append(tbname2).Append(" ALTER COLUMN ").Append(colname2).Append(" SET DEFAULT null;\r\n"); - sb.Append("DROP SEQUENCE IF EXISTS ").Append(seqname).Append(";\r\n"); - if (seqcol.Item3) { - sb.Append("CREATE SEQUENCE ").Append(seqname).Append(";\r\n"); - sb.Append("ALTER TABLE ").Append(tbname2).Append(" ALTER COLUMN ").Append(colname2).Append(" SET DEFAULT nextval('").Append(seqname).Append("'::regclass);\r\n"); - sb.Append(" SELECT case when max(").Append(colname2).Append(") is null then 0 else setval('").Append(seqname).Append("', max(").Append(colname2).Append(")) end FROM ").Append(tbname2).Append(";\r\n"); - } - } - return sb.Length == 0 ? null : sb.ToString(); - } - } + //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 + var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"); + var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.FreeSqlTmp_{tbname[1]}"); + //创建临时表 + sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(","); + if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, true)); + } + if (tb.Primarys.Any()) + { + sb.Append(" \r\n CONSTRAINT ").Append(tbname[0]).Append("_").Append(tbname[1]).Append("_pkey PRIMARY KEY ("); + foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1); + sb.Append("\r\n) WITH (OIDS=FALSE);\r\n"); + //备注 + foreach (var tbcol in tb.Columns.Values) + { + if (string.IsNullOrEmpty(tbcol.Comment) == false) + sb.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.FreeSqlTmp_{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n"); + } + sb.Append("INSERT INTO ").Append(tmptablename).Append(" ("); + foreach (var tbcol in tb.Columns.Values) + sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append(")\r\nSELECT "); + foreach (var tbcol in tb.Columns.Values) + { + var insertvalue = "NULL"; + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) + insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) + insertvalue = $"coalesce({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + } + else if (tbcol.Attribute.IsNullable == false) + insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + sb.Append(insertvalue).Append(", "); + } + sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); + sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n"); + sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName(tbname[1])).Append(";\r\n"); + } + foreach (var seqcol in seqcols) + { + var tbname = seqcol.Item2; + var seqname = Utils.GetCsName($"{tbname[0]}.{tbname[1]}_{seqcol.Item1.Attribute.Name}_sequence_name"); + var tbname2 = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}"); + var colname2 = _commonUtils.QuoteSqlName(seqcol.Item1.Attribute.Name); + sb.Append("ALTER TABLE ").Append(tbname2).Append(" ALTER COLUMN ").Append(colname2).Append(" SET DEFAULT null;\r\n"); + sb.Append("DROP SEQUENCE IF EXISTS ").Append(seqname).Append(";\r\n"); + if (seqcol.Item3) + { + sb.Append("CREATE SEQUENCE ").Append(seqname).Append(";\r\n"); + sb.Append("ALTER TABLE ").Append(tbname2).Append(" ALTER COLUMN ").Append(colname2).Append(" SET DEFAULT nextval('").Append(seqname).Append("'::regclass);\r\n"); + sb.Append(" SELECT case when max(").Append(colname2).Append(") is null then 0 else setval('").Append(seqname).Append("', max(").Append(colname2).Append(")) end FROM ").Append(tbname2).Append(";\r\n"); + } + } + return sb.Length == 0 ? null : sb.ToString(); + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLDbFirst.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLDbFirst.cs index 2db33d75..517b8370 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLDbFirst.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLDbFirst.cs @@ -14,211 +14,220 @@ using System.Net; using System.Net.NetworkInformation; using System.Text.RegularExpressions; -namespace FreeSql.PostgreSQL { - class PostgreSQLDbFirst : IDbFirst { - IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - public PostgreSQLDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - } +namespace FreeSql.PostgreSQL +{ + class PostgreSQLDbFirst : IDbFirst + { + IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + public PostgreSQLDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + } - public int GetDbType(DbColumnInfo column) => (int)GetNpgsqlDbType(column); - NpgsqlDbType GetNpgsqlDbType(DbColumnInfo column) { - var dbtype = column.DbTypeText; - var isarray = dbtype.EndsWith("[]"); - if (isarray) dbtype = dbtype.Remove(dbtype.Length - 2); - NpgsqlDbType ret = NpgsqlDbType.Unknown; - switch (dbtype.ToLower().TrimStart('_')) { - case "int2": ret = NpgsqlDbType.Smallint;break; - case "int4": ret = NpgsqlDbType.Integer; break; - case "int8": ret = NpgsqlDbType.Bigint; break; - case "numeric": ret = NpgsqlDbType.Numeric; break; - case "float4": ret = NpgsqlDbType.Real; break; - case "float8": ret = NpgsqlDbType.Double; break; - case "money": ret = NpgsqlDbType.Money; break; + public int GetDbType(DbColumnInfo column) => (int)GetNpgsqlDbType(column); + NpgsqlDbType GetNpgsqlDbType(DbColumnInfo column) + { + var dbtype = column.DbTypeText; + var isarray = dbtype.EndsWith("[]"); + if (isarray) dbtype = dbtype.Remove(dbtype.Length - 2); + NpgsqlDbType ret = NpgsqlDbType.Unknown; + switch (dbtype.ToLower().TrimStart('_')) + { + case "int2": ret = NpgsqlDbType.Smallint; break; + case "int4": ret = NpgsqlDbType.Integer; break; + case "int8": ret = NpgsqlDbType.Bigint; break; + case "numeric": ret = NpgsqlDbType.Numeric; break; + case "float4": ret = NpgsqlDbType.Real; break; + case "float8": ret = NpgsqlDbType.Double; break; + case "money": ret = NpgsqlDbType.Money; break; - case "bpchar": ret = NpgsqlDbType.Char; break; - case "varchar": ret = NpgsqlDbType.Varchar; break; - case "text": ret = NpgsqlDbType.Text; break; + case "bpchar": ret = NpgsqlDbType.Char; break; + case "varchar": ret = NpgsqlDbType.Varchar; break; + case "text": ret = NpgsqlDbType.Text; break; - case "timestamp": ret = NpgsqlDbType.Timestamp; break; - case "timestamptz": ret = NpgsqlDbType.TimestampTz; break; - case "date": ret = NpgsqlDbType.Date; break; - case "time": ret = NpgsqlDbType.Time; break; - case "timetz": ret = NpgsqlDbType.TimeTz; break; - case "interval": ret = NpgsqlDbType.Interval; break; + case "timestamp": ret = NpgsqlDbType.Timestamp; break; + case "timestamptz": ret = NpgsqlDbType.TimestampTz; break; + case "date": ret = NpgsqlDbType.Date; break; + case "time": ret = NpgsqlDbType.Time; break; + case "timetz": ret = NpgsqlDbType.TimeTz; break; + case "interval": ret = NpgsqlDbType.Interval; break; - case "bool": ret = NpgsqlDbType.Boolean; break; - case "bytea": ret = NpgsqlDbType.Bytea; break; - case "bit": ret = NpgsqlDbType.Bit; break; - case "varbit": ret = NpgsqlDbType.Varbit; break; + case "bool": ret = NpgsqlDbType.Boolean; break; + case "bytea": ret = NpgsqlDbType.Bytea; break; + case "bit": ret = NpgsqlDbType.Bit; break; + case "varbit": ret = NpgsqlDbType.Varbit; break; - case "point": ret = NpgsqlDbType.Point; break; - case "line": ret = NpgsqlDbType.Line; break; - case "lseg": ret = NpgsqlDbType.LSeg; break; - case "box": ret = NpgsqlDbType.Box; break; - case "path": ret = NpgsqlDbType.Path; break; - case "polygon": ret = NpgsqlDbType.Polygon; break; - case "circle": ret = NpgsqlDbType.Circle; break; + case "point": ret = NpgsqlDbType.Point; break; + case "line": ret = NpgsqlDbType.Line; break; + case "lseg": ret = NpgsqlDbType.LSeg; break; + case "box": ret = NpgsqlDbType.Box; break; + case "path": ret = NpgsqlDbType.Path; break; + case "polygon": ret = NpgsqlDbType.Polygon; break; + case "circle": ret = NpgsqlDbType.Circle; break; - case "cidr": ret = NpgsqlDbType.Cidr; break; - case "inet": ret = NpgsqlDbType.Inet; break; - case "macaddr": ret = NpgsqlDbType.MacAddr; break; + case "cidr": ret = NpgsqlDbType.Cidr; break; + case "inet": ret = NpgsqlDbType.Inet; break; + case "macaddr": ret = NpgsqlDbType.MacAddr; break; - case "json": ret = NpgsqlDbType.Json; break; - case "jsonb": ret = NpgsqlDbType.Jsonb; break; - case "uuid": ret = NpgsqlDbType.Uuid; break; + case "json": ret = NpgsqlDbType.Json; break; + case "jsonb": ret = NpgsqlDbType.Jsonb; break; + case "uuid": ret = NpgsqlDbType.Uuid; break; - case "int4range": ret = NpgsqlDbType.Range | NpgsqlDbType.Integer; break; - case "int8range": ret = NpgsqlDbType.Range | NpgsqlDbType.Bigint; break; - case "numrange": ret = NpgsqlDbType.Range | NpgsqlDbType.Numeric; break; - case "tsrange": ret = NpgsqlDbType.Range | NpgsqlDbType.Timestamp; break; - case "tstzrange": ret = NpgsqlDbType.Range | NpgsqlDbType.TimestampTz; break; - case "daterange": ret = NpgsqlDbType.Range | NpgsqlDbType.Date; break; + case "int4range": ret = NpgsqlDbType.Range | NpgsqlDbType.Integer; break; + case "int8range": ret = NpgsqlDbType.Range | NpgsqlDbType.Bigint; break; + case "numrange": ret = NpgsqlDbType.Range | NpgsqlDbType.Numeric; break; + case "tsrange": ret = NpgsqlDbType.Range | NpgsqlDbType.Timestamp; break; + case "tstzrange": ret = NpgsqlDbType.Range | NpgsqlDbType.TimestampTz; break; + case "daterange": ret = NpgsqlDbType.Range | NpgsqlDbType.Date; break; - case "hstore": ret = NpgsqlDbType.Hstore; break; - case "geometry": ret = NpgsqlDbType.Geometry; break; - } - return isarray ? (ret | NpgsqlDbType.Array) : ret; - } + case "hstore": ret = NpgsqlDbType.Hstore; break; + case "geometry": ret = NpgsqlDbType.Geometry; break; + } + return isarray ? (ret | NpgsqlDbType.Array) : ret; + } - static readonly Dictionary _dicDbToCs = new Dictionary() { - { (int)NpgsqlDbType.Smallint, ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, - { (int)NpgsqlDbType.Integer, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, - { (int)NpgsqlDbType.Bigint, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, - { (int)NpgsqlDbType.Numeric, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, - { (int)NpgsqlDbType.Real, ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, - { (int)NpgsqlDbType.Double, ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, - { (int)NpgsqlDbType.Money, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, + static readonly Dictionary _dicDbToCs = new Dictionary() { + { (int)NpgsqlDbType.Smallint, ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, + { (int)NpgsqlDbType.Integer, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, + { (int)NpgsqlDbType.Bigint, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, + { (int)NpgsqlDbType.Numeric, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, + { (int)NpgsqlDbType.Real, ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, + { (int)NpgsqlDbType.Double, ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, + { (int)NpgsqlDbType.Money, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, - { (int)NpgsqlDbType.Char, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)NpgsqlDbType.Varchar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)NpgsqlDbType.Text, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)NpgsqlDbType.Char, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)NpgsqlDbType.Varchar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)NpgsqlDbType.Text, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)NpgsqlDbType.Timestamp, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)NpgsqlDbType.TimestampTz, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)NpgsqlDbType.Date, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)NpgsqlDbType.Time, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, - { (int)NpgsqlDbType.TimeTz, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, - { (int)NpgsqlDbType.Interval, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, + { (int)NpgsqlDbType.Timestamp, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)NpgsqlDbType.TimestampTz, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)NpgsqlDbType.Date, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)NpgsqlDbType.Time, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, + { (int)NpgsqlDbType.TimeTz, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, + { (int)NpgsqlDbType.Interval, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, - { (int)NpgsqlDbType.Boolean, ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, - { (int)NpgsqlDbType.Bytea, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Bit, ("(BitArray)", "{0}.ToBitArray()", "{0}.To1010()", "BitArray", typeof(BitArray), typeof(BitArray), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Varbit, ("(BitArray)", "{0}.ToBitArray()", "{0}.To1010()", "BitArray", typeof(BitArray), typeof(BitArray), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Boolean, ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, + { (int)NpgsqlDbType.Bytea, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Bit, ("(BitArray)", "{0}.ToBitArray()", "{0}.To1010()", "BitArray", typeof(BitArray), typeof(BitArray), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Varbit, ("(BitArray)", "{0}.ToBitArray()", "{0}.To1010()", "BitArray", typeof(BitArray), typeof(BitArray), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Point, ("(NpgsqlPoint?)", "NpgsqlPoint.Parse({0})", "{0}.ToString()", "NpgsqlPoint", typeof(NpgsqlPoint), typeof(NpgsqlPoint?), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Line, ("(NpgsqlLine?)", "NpgsqlLine.Parse({0})", "{0}.ToString()", "NpgsqlLine", typeof(NpgsqlLine), typeof(NpgsqlLine?), "{0}", "GetValue") }, - { (int)NpgsqlDbType.LSeg, ("(NpgsqlLSeg?)", "NpgsqlLSeg.Parse({0})", "{0}.ToString()", "NpgsqlLSeg", typeof(NpgsqlLSeg), typeof(NpgsqlLSeg?), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Box, ("(NpgsqlBox?)", "NpgsqlBox.Parse({0})", "{0}.ToString()", "NpgsqlBox", typeof(NpgsqlBox), typeof(NpgsqlBox?), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Path, ("(NpgsqlPath?)", "NpgsqlPath.Parse({0})", "{0}.ToString()", "NpgsqlPath", typeof(NpgsqlPath), typeof(NpgsqlPath?), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Polygon, ("(NpgsqlPolygon?)", "NpgsqlPolygon.Parse({0})", "{0}.ToString()", "NpgsqlPolygon", typeof(NpgsqlPolygon), typeof(NpgsqlPolygon?), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Circle, ("(NpgsqlCircle?)", "NpgsqlCircle.Parse({0})", "{0}.ToString()", "NpgsqlCircle", typeof(NpgsqlCircle), typeof(NpgsqlCircle?), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Point, ("(NpgsqlPoint?)", "NpgsqlPoint.Parse({0})", "{0}.ToString()", "NpgsqlPoint", typeof(NpgsqlPoint), typeof(NpgsqlPoint?), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Line, ("(NpgsqlLine?)", "NpgsqlLine.Parse({0})", "{0}.ToString()", "NpgsqlLine", typeof(NpgsqlLine), typeof(NpgsqlLine?), "{0}", "GetValue") }, + { (int)NpgsqlDbType.LSeg, ("(NpgsqlLSeg?)", "NpgsqlLSeg.Parse({0})", "{0}.ToString()", "NpgsqlLSeg", typeof(NpgsqlLSeg), typeof(NpgsqlLSeg?), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Box, ("(NpgsqlBox?)", "NpgsqlBox.Parse({0})", "{0}.ToString()", "NpgsqlBox", typeof(NpgsqlBox), typeof(NpgsqlBox?), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Path, ("(NpgsqlPath?)", "NpgsqlPath.Parse({0})", "{0}.ToString()", "NpgsqlPath", typeof(NpgsqlPath), typeof(NpgsqlPath?), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Polygon, ("(NpgsqlPolygon?)", "NpgsqlPolygon.Parse({0})", "{0}.ToString()", "NpgsqlPolygon", typeof(NpgsqlPolygon), typeof(NpgsqlPolygon?), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Circle, ("(NpgsqlCircle?)", "NpgsqlCircle.Parse({0})", "{0}.ToString()", "NpgsqlCircle", typeof(NpgsqlCircle), typeof(NpgsqlCircle?), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Cidr, ("((IPAddress, int)?)", "(IPAddress, int)({0})", "{0}.ToString()", "(IPAddress, int)", typeof((IPAddress, int)), typeof((IPAddress, int)?), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Inet, ("(IPAddress)", "IPAddress.Parse({0})", "{0}.ToString()", "IPAddress", typeof(IPAddress), typeof(IPAddress), "{0}", "GetValue") }, - { (int)NpgsqlDbType.MacAddr, ("(PhysicalAddress?)", "PhysicalAddress.Parse({0})", "{0}.ToString()", "PhysicalAddress", typeof(PhysicalAddress), typeof(PhysicalAddress), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Cidr, ("((IPAddress, int)?)", "(IPAddress, int)({0})", "{0}.ToString()", "(IPAddress, int)", typeof((IPAddress, int)), typeof((IPAddress, int)?), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Inet, ("(IPAddress)", "IPAddress.Parse({0})", "{0}.ToString()", "IPAddress", typeof(IPAddress), typeof(IPAddress), "{0}", "GetValue") }, + { (int)NpgsqlDbType.MacAddr, ("(PhysicalAddress?)", "PhysicalAddress.Parse({0})", "{0}.ToString()", "PhysicalAddress", typeof(PhysicalAddress), typeof(PhysicalAddress), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Json, ("(JToken)", "JToken.Parse({0})", "{0}.ToString()", "JToken", typeof(JToken), typeof(JToken), "{0}", "GetString") }, - { (int)NpgsqlDbType.Jsonb, ("(JToken)", "JToken.Parse({0})", "{0}.ToString()", "JToken", typeof(JToken), typeof(JToken), "{0}", "GetString") }, - { (int)NpgsqlDbType.Uuid, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid", typeof(Guid), typeof(Guid?), "{0}", "GetString") }, + { (int)NpgsqlDbType.Json, ("(JToken)", "JToken.Parse({0})", "{0}.ToString()", "JToken", typeof(JToken), typeof(JToken), "{0}", "GetString") }, + { (int)NpgsqlDbType.Jsonb, ("(JToken)", "JToken.Parse({0})", "{0}.ToString()", "JToken", typeof(JToken), typeof(JToken), "{0}", "GetString") }, + { (int)NpgsqlDbType.Uuid, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid", typeof(Guid), typeof(Guid?), "{0}", "GetString") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Integer), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Bigint), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Numeric), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Timestamp), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.TimestampTz), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Date), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Integer), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Bigint), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Numeric), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Timestamp), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.TimestampTz), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Date), ("(NpgsqlRange?)", "{0}.ToNpgsqlRange()", "{0}.ToString()", "NpgsqlRange", typeof(NpgsqlRange), typeof(NpgsqlRange?), "{0}", "GetString") }, - { (int)NpgsqlDbType.Hstore, ("(Dictionary)", "JsonConvert.DeserializeObject>({0})", "JsonConvert.SerializeObject({0})", "Dictionary", typeof(Dictionary), typeof(Dictionary), "{0}", "GetValue") }, - { (int)NpgsqlDbType.Geometry, ("(PostgisGeometry)", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "PostgisGeometry", typeof(PostgisGeometry), typeof(PostgisGeometry), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Hstore, ("(Dictionary)", "JsonConvert.DeserializeObject>({0})", "JsonConvert.SerializeObject({0})", "Dictionary", typeof(Dictionary), typeof(Dictionary), "{0}", "GetValue") }, + { (int)NpgsqlDbType.Geometry, ("(PostgisGeometry)", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "PostgisGeometry", typeof(PostgisGeometry), typeof(PostgisGeometry), "{0}", "GetValue") }, /*** array ***/ { (int)(NpgsqlDbType.Smallint | NpgsqlDbType.Array), ("(short[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "short[]", typeof(short[]), typeof(short[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Integer | NpgsqlDbType.Array), ("(int[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "int[]", typeof(int[]), typeof(int[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Bigint | NpgsqlDbType.Array), ("(long[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "long[]", typeof(long[]), typeof(long[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Numeric | NpgsqlDbType.Array), ("(decimal[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "decimal[]", typeof(decimal[]), typeof(decimal[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Real | NpgsqlDbType.Array), ("(float[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "float[]", typeof(float[]), typeof(float[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Double | NpgsqlDbType.Array), ("(double[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "double[]", typeof(double[]), typeof(double[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Money | NpgsqlDbType.Array), ("(decimal[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "decimal[]", typeof(decimal[]), typeof(decimal[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Integer | NpgsqlDbType.Array), ("(int[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "int[]", typeof(int[]), typeof(int[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Bigint | NpgsqlDbType.Array), ("(long[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "long[]", typeof(long[]), typeof(long[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Numeric | NpgsqlDbType.Array), ("(decimal[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "decimal[]", typeof(decimal[]), typeof(decimal[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Real | NpgsqlDbType.Array), ("(float[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "float[]", typeof(float[]), typeof(float[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Double | NpgsqlDbType.Array), ("(double[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "double[]", typeof(double[]), typeof(double[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Money | NpgsqlDbType.Array), ("(decimal[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "decimal[]", typeof(decimal[]), typeof(decimal[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Char | NpgsqlDbType.Array), ("(string[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "string[]", typeof(string[]), typeof(string[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Varchar | NpgsqlDbType.Array), ("(string[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "string[]", typeof(string[]), typeof(string[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Text | NpgsqlDbType.Array), ("(string[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "string[]", typeof(string[]), typeof(string[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Char | NpgsqlDbType.Array), ("(string[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "string[]", typeof(string[]), typeof(string[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Varchar | NpgsqlDbType.Array), ("(string[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "string[]", typeof(string[]), typeof(string[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Text | NpgsqlDbType.Array), ("(string[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "string[]", typeof(string[]), typeof(string[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Timestamp | NpgsqlDbType.Array), ("(DateTime[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "DateTime[]", typeof(DateTime[]), typeof(DateTime[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.TimestampTz | NpgsqlDbType.Array), ("(DateTime[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "DateTime[]", typeof(DateTime[]), typeof(DateTime[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Date | NpgsqlDbType.Array), ("(DateTime[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "DateTime[]", typeof(DateTime[]), typeof(DateTime[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Time | NpgsqlDbType.Array), ("(TimeSpan[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "TimeSpan[]", typeof(TimeSpan[]), typeof(TimeSpan[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.TimeTz | NpgsqlDbType.Array), ("(TimeSpan[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "TimeSpan[]", typeof(TimeSpan[]), typeof(TimeSpan[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Interval | NpgsqlDbType.Array), ("(TimeSpan[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "TimeSpan[]", typeof(TimeSpan[]), typeof(TimeSpan[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Timestamp | NpgsqlDbType.Array), ("(DateTime[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "DateTime[]", typeof(DateTime[]), typeof(DateTime[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.TimestampTz | NpgsqlDbType.Array), ("(DateTime[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "DateTime[]", typeof(DateTime[]), typeof(DateTime[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Date | NpgsqlDbType.Array), ("(DateTime[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "DateTime[]", typeof(DateTime[]), typeof(DateTime[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Time | NpgsqlDbType.Array), ("(TimeSpan[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "TimeSpan[]", typeof(TimeSpan[]), typeof(TimeSpan[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.TimeTz | NpgsqlDbType.Array), ("(TimeSpan[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "TimeSpan[]", typeof(TimeSpan[]), typeof(TimeSpan[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Interval | NpgsqlDbType.Array), ("(TimeSpan[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "TimeSpan[]", typeof(TimeSpan[]), typeof(TimeSpan[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Boolean | NpgsqlDbType.Array), ("(bool[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "bool[]", typeof(bool[]), typeof(bool[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Bytea | NpgsqlDbType.Array), ("(byte[][])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "byte[][]", typeof(byte[][]), typeof(byte[][]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Bit | NpgsqlDbType.Array), ("(BitArray[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "BitArray[]", typeof(BitArray[]), typeof(BitArray[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Varbit | NpgsqlDbType.Array), ("(BitArray[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "BitArray[]", typeof(BitArray[]), typeof(BitArray[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Boolean | NpgsqlDbType.Array), ("(bool[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "bool[]", typeof(bool[]), typeof(bool[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Bytea | NpgsqlDbType.Array), ("(byte[][])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "byte[][]", typeof(byte[][]), typeof(byte[][]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Bit | NpgsqlDbType.Array), ("(BitArray[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "BitArray[]", typeof(BitArray[]), typeof(BitArray[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Varbit | NpgsqlDbType.Array), ("(BitArray[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "BitArray[]", typeof(BitArray[]), typeof(BitArray[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Point | NpgsqlDbType.Array), ("(NpgsqlPoint[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlPoint[]", typeof(NpgsqlPoint[]), typeof(NpgsqlPoint[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Line | NpgsqlDbType.Array), ("(NpgsqlLine[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlLine[]", typeof(NpgsqlLine[]), typeof(NpgsqlLine[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.LSeg | NpgsqlDbType.Array), ("(NpgsqlLSeg[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlLSeg[]", typeof(NpgsqlLSeg[]), typeof(NpgsqlLSeg[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Box | NpgsqlDbType.Array), ("(NpgsqlBox[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlBox[]", typeof(NpgsqlBox[]), typeof(NpgsqlBox[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Path | NpgsqlDbType.Array), ("(NpgsqlPath[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlPath[]", typeof(NpgsqlPath[]), typeof(NpgsqlPath[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Polygon | NpgsqlDbType.Array), ("(NpgsqlPolygon[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlPolygon[]", typeof(NpgsqlPolygon[]), typeof(NpgsqlPolygon[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Circle | NpgsqlDbType.Array), ("(NpgsqlCircle[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlCircle[]", typeof(NpgsqlCircle[]), typeof(NpgsqlCircle[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Point | NpgsqlDbType.Array), ("(NpgsqlPoint[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlPoint[]", typeof(NpgsqlPoint[]), typeof(NpgsqlPoint[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Line | NpgsqlDbType.Array), ("(NpgsqlLine[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlLine[]", typeof(NpgsqlLine[]), typeof(NpgsqlLine[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.LSeg | NpgsqlDbType.Array), ("(NpgsqlLSeg[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlLSeg[]", typeof(NpgsqlLSeg[]), typeof(NpgsqlLSeg[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Box | NpgsqlDbType.Array), ("(NpgsqlBox[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlBox[]", typeof(NpgsqlBox[]), typeof(NpgsqlBox[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Path | NpgsqlDbType.Array), ("(NpgsqlPath[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlPath[]", typeof(NpgsqlPath[]), typeof(NpgsqlPath[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Polygon | NpgsqlDbType.Array), ("(NpgsqlPolygon[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlPolygon[]", typeof(NpgsqlPolygon[]), typeof(NpgsqlPolygon[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Circle | NpgsqlDbType.Array), ("(NpgsqlCircle[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "NpgsqlCircle[]", typeof(NpgsqlCircle[]), typeof(NpgsqlCircle[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Cidr | NpgsqlDbType.Array), ("((IPAddress, int)[])", "JsonConvert.DeserializeObject<(IPAddress, int)[]>({0})", "JsonConvert.SerializeObject({0})", "(IPAddress, int)[]", typeof((IPAddress, int)[]), typeof((IPAddress, int)[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Inet | NpgsqlDbType.Array), ("(IPAddress[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "IPAddress[]", typeof(IPAddress[]), typeof(IPAddress[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.MacAddr | NpgsqlDbType.Array), ("(PhysicalAddress[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "PhysicalAddress[]", typeof(PhysicalAddress[]), typeof(PhysicalAddress[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Cidr | NpgsqlDbType.Array), ("((IPAddress, int)[])", "JsonConvert.DeserializeObject<(IPAddress, int)[]>({0})", "JsonConvert.SerializeObject({0})", "(IPAddress, int)[]", typeof((IPAddress, int)[]), typeof((IPAddress, int)[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Inet | NpgsqlDbType.Array), ("(IPAddress[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "IPAddress[]", typeof(IPAddress[]), typeof(IPAddress[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.MacAddr | NpgsqlDbType.Array), ("(PhysicalAddress[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "PhysicalAddress[]", typeof(PhysicalAddress[]), typeof(PhysicalAddress[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Json | NpgsqlDbType.Array), ("(JToken[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "JToken[]", typeof(JToken[]), typeof(JToken[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Jsonb | NpgsqlDbType.Array), ("(JToken[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "JToken[]", typeof(JToken[]), typeof(JToken[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Uuid | NpgsqlDbType.Array), ("(Guid[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "Guid[]", typeof(Guid[]), typeof(Guid[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Json | NpgsqlDbType.Array), ("(JToken[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "JToken[]", typeof(JToken[]), typeof(JToken[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Jsonb | NpgsqlDbType.Array), ("(JToken[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "JToken[]", typeof(JToken[]), typeof(JToken[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Uuid | NpgsqlDbType.Array), ("(Guid[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "Guid[]", typeof(Guid[]), typeof(Guid[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Integer | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Bigint | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Numeric | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Timestamp | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.TimestampTz | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Range | NpgsqlDbType.Date | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Integer | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Bigint | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Numeric | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Timestamp | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.TimestampTz | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Range | NpgsqlDbType.Date | NpgsqlDbType.Array), ("(NpgsqlRange[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "NpgsqlRange[]", typeof(NpgsqlRange[]), typeof(NpgsqlRange[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Hstore | NpgsqlDbType.Array), ("(Dictionary[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "Dictionary[]", typeof(Dictionary[]), typeof(Dictionary[]), "{0}", "GetValue") }, - { (int)(NpgsqlDbType.Geometry | NpgsqlDbType.Array), ("(PostgisGeometry[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "PostgisGeometry[]", typeof(PostgisGeometry[]), typeof(PostgisGeometry[]), "{0}", "GetValue") }, - }; + { (int)(NpgsqlDbType.Hstore | NpgsqlDbType.Array), ("(Dictionary[])", "JsonConvert.DeserializeObject[]>({0})", "JsonConvert.SerializeObject({0})", "Dictionary[]", typeof(Dictionary[]), typeof(Dictionary[]), "{0}", "GetValue") }, + { (int)(NpgsqlDbType.Geometry | NpgsqlDbType.Array), ("(PostgisGeometry[])", "JsonConvert.DeserializeObject({0})", "JsonConvert.SerializeObject({0})", "PostgisGeometry[]", typeof(PostgisGeometry[]), typeof(PostgisGeometry[]), "{0}", "GetValue") }, + }; - public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; - public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csParse : null; - public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csStringify : null; - public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; - public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeInfo : null; - public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeValue : null; - public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.dataReaderMethod : null; + public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; + public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csParse : null; + public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csStringify : null; + public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; + public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeInfo : null; + public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeValue : null; + public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.dataReaderMethod : null; - public List GetDatabases() { - var sql = @" select datname from pg_database where datname not in ('template1', 'template0')"; - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); - } + public List GetDatabases() + { + var sql = @" select datname from pg_database where datname not in ('template1', 'template0')"; + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); + } - public List GetTablesByDatabase(params string[] database) { - var olddatabase = ""; - using (var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5))) { - olddatabase = conn.Value.Database; - } - var dbs = database == null || database.Any() == false ? new[] { olddatabase } : database; - var tables = new List(); + public List GetTablesByDatabase(params string[] database) + { + var olddatabase = ""; + using (var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5))) + { + olddatabase = conn.Value.Database; + } + var dbs = database == null || database.Any() == false ? new[] { olddatabase } : database; + var tables = new List(); - foreach (var db in dbs) { - if (string.IsNullOrEmpty(db) || string.Compare(db, olddatabase, true) != 0) continue; + foreach (var db in dbs) + { + if (string.IsNullOrEmpty(db) || string.Compare(db, olddatabase, true) != 0) continue; - var loc1 = new List(); - var loc2 = new Dictionary(); - var loc3 = new Dictionary>(); + var loc1 = new List(); + var loc2 = new Dictionary(); + var loc3 = new Dictionary>(); - var sql = $@" + var sql = $@" select b.nspname || '.' || a.tablename, a.schemaname, @@ -246,34 +255,36 @@ left join pg_description d on d.objoid = a.oid and objsubid = 0 where b.nspname not in ('pg_catalog', 'information_schema') and a.relkind in ('m','v') and b.nspname || '.' || a.relname not in ('public.geography_columns','public.geometry_columns','public.raster_columns','public.raster_overviews') "; - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var loc6 = new List(); - var loc66 = new List(); - foreach (object[] row in ds) { - var object_id = string.Concat(row[0]); - var owner = string.Concat(row[1]); - var table = string.Concat(row[2]); - var comment = string.Concat(row[3]); - Enum.TryParse(string.Concat(row[4]), out var type); - loc2.Add(object_id, new DbTableInfo { Id = object_id.ToString(), Schema = owner, Name = table, Comment = comment, Type = type }); - loc3.Add(object_id, new Dictionary()); - switch (type) { - case DbTableType.VIEW: - case DbTableType.TABLE: - loc6.Add(object_id); - break; - case DbTableType.StoreProcedure: - loc66.Add(object_id); - break; - } - } - if (loc6.Count == 0) return loc1; - string loc8 = "'" + string.Join("','", loc6.ToArray()) + "'"; - string loc88 = "'" + string.Join("','", loc66.ToArray()) + "'"; + var loc6 = new List(); + var loc66 = new List(); + foreach (object[] row in ds) + { + var object_id = string.Concat(row[0]); + var owner = string.Concat(row[1]); + var table = string.Concat(row[2]); + var comment = string.Concat(row[3]); + Enum.TryParse(string.Concat(row[4]), out var type); + loc2.Add(object_id, new DbTableInfo { Id = object_id.ToString(), Schema = owner, Name = table, Comment = comment, Type = type }); + loc3.Add(object_id, new Dictionary()); + switch (type) + { + case DbTableType.VIEW: + case DbTableType.TABLE: + loc6.Add(object_id); + break; + case DbTableType.StoreProcedure: + loc66.Add(object_id); + break; + } + } + if (loc6.Count == 0) return loc1; + string loc8 = "'" + string.Join("','", loc6.ToArray()) + "'"; + string loc88 = "'" + string.Join("','", loc66.ToArray()) + "'"; - sql = $@" + sql = $@" select ns.nspname || '.' || c.relname as id, a.attname, @@ -297,49 +308,53 @@ left join pg_attrdef e on e.adrelid = a.attrelid and e.adnum = a.attnum inner join pg_namespace ns on ns.oid = c.relnamespace inner join pg_namespace ns2 on ns2.oid = t.typnamespace where ns.nspname || '.' || c.relname in ({loc8})"; - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - foreach (object[] row in ds) { - var object_id = string.Concat(row[0]); - var column = string.Concat(row[1]); - var type = string.Concat(row[2]); - var max_length = int.Parse(string.Concat(row[3])); - var sqlType = string.Concat(row[4]); - var is_nullable = string.Concat(row[5]) == "1"; - var is_identity = string.Concat(row[6]).StartsWith(@"nextval('") && string.Concat(row[6]).EndsWith(@"'::regclass)"); - var comment = string.Concat(row[7]); - int attndims = int.Parse(string.Concat(row[8])); - string typtype = string.Concat(row[9]); - string owner = string.Concat(row[10]); - int attnum = int.Parse(string.Concat(row[11])); - switch (sqlType.ToLower()) { - case "bool": case "name": case "bit": case "varbit": case "bpchar": case "varchar": case "bytea": case "text": case "uuid": break; - default: max_length *= 8; break; - } - if (max_length <= 0) max_length = -1; - if (type.StartsWith("_")) { - type = type.Substring(1); - if (attndims == 0) attndims++; - } - if (sqlType.StartsWith("_")) sqlType = sqlType.Substring(1); + foreach (object[] row in ds) + { + var object_id = string.Concat(row[0]); + var column = string.Concat(row[1]); + var type = string.Concat(row[2]); + var max_length = int.Parse(string.Concat(row[3])); + var sqlType = string.Concat(row[4]); + var is_nullable = string.Concat(row[5]) == "1"; + var is_identity = string.Concat(row[6]).StartsWith(@"nextval('") && string.Concat(row[6]).EndsWith(@"'::regclass)"); + var comment = string.Concat(row[7]); + int attndims = int.Parse(string.Concat(row[8])); + string typtype = string.Concat(row[9]); + string owner = string.Concat(row[10]); + int attnum = int.Parse(string.Concat(row[11])); + switch (sqlType.ToLower()) + { + case "bool": case "name": case "bit": case "varbit": case "bpchar": case "varchar": case "bytea": case "text": case "uuid": break; + default: max_length *= 8; break; + } + if (max_length <= 0) max_length = -1; + if (type.StartsWith("_")) + { + type = type.Substring(1); + if (attndims == 0) attndims++; + } + if (sqlType.StartsWith("_")) sqlType = sqlType.Substring(1); - loc3[object_id].Add(column, new DbColumnInfo { - Name = column, - MaxLength = max_length, - IsIdentity = is_identity, - IsNullable = is_nullable, - IsPrimary = false, - DbTypeText = type, - DbTypeTextFull = sqlType, - Table = loc2[object_id], - Coment = comment - }); - loc3[object_id][column].DbType = this.GetDbType(loc3[object_id][column]); - loc3[object_id][column].CsType = this.GetCsTypeInfo(loc3[object_id][column]); - } + loc3[object_id].Add(column, new DbColumnInfo + { + Name = column, + MaxLength = max_length, + IsIdentity = is_identity, + IsNullable = is_nullable, + IsPrimary = false, + DbTypeText = type, + DbTypeTextFull = sqlType, + Table = loc2[object_id], + Coment = comment + }); + loc3[object_id][column].DbType = this.GetDbType(loc3[object_id][column]); + loc3[object_id][column].CsType = this.GetCsTypeInfo(loc3[object_id][column]); + } - sql = $@" + sql = $@" select ns.nspname || '.' || d.relname as table_id, c.attname, @@ -357,59 +372,66 @@ inner join pg_namespace ns on ns.oid = b.relnamespace inner join pg_class d on d.oid = a.indrelid where ns.nspname || '.' || d.relname in ({loc8}) "; - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var indexColumns = new Dictionary>>(); - var uniqueColumns = new Dictionary>>(); - foreach (object[] row in ds) { - var object_id = string.Concat(row[0]); - var column = string.Concat(row[1]); - var index_id = string.Concat(row[2]); - var is_unique = string.Concat(row[3]) == "1"; - var is_primary_key = string.Concat(row[4]) == "1"; - var is_clustered = string.Concat(row[5]) == "1"; - var is_desc = int.Parse(string.Concat(row[6])); - var inkey = string.Concat(row[7]).Split(' '); - var attnum = int.Parse(string.Concat(row[8])); - attnum = int.Parse(inkey[attnum - 1]); - foreach (string tc in loc3[object_id].Keys) { - if (loc3[object_id][tc].DbTypeText.EndsWith("[]")) { - column = tc; - break; - } - } - if (loc3.ContainsKey(object_id) == false || loc3[object_id].ContainsKey(column) == false) continue; - var loc9 = loc3[object_id][column]; - if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; + var indexColumns = new Dictionary>>(); + var uniqueColumns = new Dictionary>>(); + foreach (object[] row in ds) + { + var object_id = string.Concat(row[0]); + var column = string.Concat(row[1]); + var index_id = string.Concat(row[2]); + var is_unique = string.Concat(row[3]) == "1"; + var is_primary_key = string.Concat(row[4]) == "1"; + var is_clustered = string.Concat(row[5]) == "1"; + var is_desc = int.Parse(string.Concat(row[6])); + var inkey = string.Concat(row[7]).Split(' '); + var attnum = int.Parse(string.Concat(row[8])); + attnum = int.Parse(inkey[attnum - 1]); + foreach (string tc in loc3[object_id].Keys) + { + if (loc3[object_id][tc].DbTypeText.EndsWith("[]")) + { + column = tc; + break; + } + } + if (loc3.ContainsKey(object_id) == false || loc3[object_id].ContainsKey(column) == false) continue; + var loc9 = loc3[object_id][column]; + if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; - Dictionary> loc10 = null; - List loc11 = null; - if (!indexColumns.TryGetValue(object_id, out loc10)) - indexColumns.Add(object_id, loc10 = new Dictionary>()); - if (!loc10.TryGetValue(index_id, out loc11)) - loc10.Add(index_id, loc11 = new List()); - loc11.Add(loc9); - if (is_unique && !is_primary_key) { - if (!uniqueColumns.TryGetValue(object_id, out loc10)) - uniqueColumns.Add(object_id, loc10 = new Dictionary>()); - if (!loc10.TryGetValue(index_id, out loc11)) - loc10.Add(index_id, loc11 = new List()); - loc11.Add(loc9); - } - } - foreach (var object_id in indexColumns.Keys) { - foreach (var column in indexColumns[object_id]) - loc2[object_id].IndexesDict.Add(column.Key, column.Value); - } - foreach (var object_id in uniqueColumns.Keys) { - foreach (var column in uniqueColumns[object_id]) { - column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); - loc2[object_id].UniquesDict.Add(column.Key, column.Value); - } - } + Dictionary> loc10 = null; + List loc11 = null; + if (!indexColumns.TryGetValue(object_id, out loc10)) + indexColumns.Add(object_id, loc10 = new Dictionary>()); + if (!loc10.TryGetValue(index_id, out loc11)) + loc10.Add(index_id, loc11 = new List()); + loc11.Add(loc9); + if (is_unique && !is_primary_key) + { + if (!uniqueColumns.TryGetValue(object_id, out loc10)) + uniqueColumns.Add(object_id, loc10 = new Dictionary>()); + if (!loc10.TryGetValue(index_id, out loc11)) + loc10.Add(index_id, loc11 = new List()); + loc11.Add(loc9); + } + } + foreach (var object_id in indexColumns.Keys) + { + foreach (var column in indexColumns[object_id]) + loc2[object_id].IndexesDict.Add(column.Key, column.Value); + } + foreach (var object_id in uniqueColumns.Keys) + { + foreach (var column in uniqueColumns[object_id]) + { + column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); + loc2[object_id].UniquesDict.Add(column.Key, column.Value); + } + } - sql = $@" + sql = $@" select ns.nspname || '.' || b.relname as table_id, array(select attname from pg_attribute where attrelid = a.conrelid and attnum = any(a.conkey)) as column_name, @@ -426,81 +448,92 @@ inner join pg_namespace ns on ns.oid = b.relnamespace inner join pg_namespace ns2 on ns2.oid = c.relnamespace where ns.nspname || '.' || b.relname in ({loc8}) "; - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var fkColumns = new Dictionary>(); - foreach (object[] row in ds) { - var table_id = string.Concat(row[0]); - var column = row[1] as string[]; - var fk_id = string.Concat(row[2]); - var ref_table_id = string.Concat(row[3]); - var is_foreign_key = string.Concat(row[4]) == "1"; - var referenced_column = row[5] as string[]; - var referenced_db = string.Concat(row[6]); - var referenced_table = string.Concat(row[7]); + var fkColumns = new Dictionary>(); + foreach (object[] row in ds) + { + var table_id = string.Concat(row[0]); + var column = row[1] as string[]; + var fk_id = string.Concat(row[2]); + var ref_table_id = string.Concat(row[3]); + var is_foreign_key = string.Concat(row[4]) == "1"; + var referenced_column = row[5] as string[]; + var referenced_db = string.Concat(row[6]); + var referenced_table = string.Concat(row[7]); - if (loc2.ContainsKey(ref_table_id) == false) continue; + if (loc2.ContainsKey(ref_table_id) == false) continue; - Dictionary loc12 = null; - DbForeignInfo loc13 = null; - if (!fkColumns.TryGetValue(table_id, out loc12)) - fkColumns.Add(table_id, loc12 = new Dictionary()); - if (!loc12.TryGetValue(fk_id, out loc13)) - loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[table_id], ReferencedTable = loc2[ref_table_id] }); + Dictionary loc12 = null; + DbForeignInfo loc13 = null; + if (!fkColumns.TryGetValue(table_id, out loc12)) + fkColumns.Add(table_id, loc12 = new Dictionary()); + if (!loc12.TryGetValue(fk_id, out loc13)) + loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[table_id], ReferencedTable = loc2[ref_table_id] }); - for (int a = 0; a < column.Length; a++) { - loc13.Columns.Add(loc3[table_id][column[a]]); - loc13.ReferencedColumns.Add(loc3[ref_table_id][referenced_column[a]]); - } - } - foreach (var table_id in fkColumns.Keys) - foreach (var fk in fkColumns[table_id]) - loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); + for (int a = 0; a < column.Length; a++) + { + loc13.Columns.Add(loc3[table_id][column[a]]); + loc13.ReferencedColumns.Add(loc3[ref_table_id][referenced_column[a]]); + } + } + foreach (var table_id in fkColumns.Keys) + foreach (var fk in fkColumns[table_id]) + loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); - foreach (var table_id in loc3.Keys) { - foreach (var loc5 in loc3[table_id].Values) { - loc2[table_id].Columns.Add(loc5); - if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); - if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); - } - } - foreach (var loc4 in loc2.Values) { - if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) { - foreach (var loc5 in loc4.UniquesDict.First().Value) { - loc5.IsPrimary = true; - loc4.Primarys.Add(loc5); - } - } - loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); - loc4.Columns.Sort((c1, c2) => { - int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); - if (compare == 0) { - bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); - bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); - compare = b2.CompareTo(b1); - } - if (compare == 0) compare = c1.Name.CompareTo(c2.Name); - return compare; - }); - loc1.Add(loc4); - } - loc1.Sort((t1, t2) => { - var ret = t1.Schema.CompareTo(t2.Schema); - if (ret == 0) ret = t1.Name.CompareTo(t2.Name); - return ret; - }); + foreach (var table_id in loc3.Keys) + { + foreach (var loc5 in loc3[table_id].Values) + { + loc2[table_id].Columns.Add(loc5); + if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); + if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); + } + } + foreach (var loc4 in loc2.Values) + { + if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) + { + foreach (var loc5 in loc4.UniquesDict.First().Value) + { + loc5.IsPrimary = true; + loc4.Primarys.Add(loc5); + } + } + loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); + loc4.Columns.Sort((c1, c2) => + { + int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); + if (compare == 0) + { + bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); + bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); + compare = b2.CompareTo(b1); + } + if (compare == 0) compare = c1.Name.CompareTo(c2.Name); + return compare; + }); + loc1.Add(loc4); + } + loc1.Sort((t1, t2) => + { + var ret = t1.Schema.CompareTo(t2.Schema); + if (ret == 0) ret = t1.Name.CompareTo(t2.Name); + return ret; + }); - loc2.Clear(); - loc3.Clear(); - tables.AddRange(loc1); - } - return tables; - } + loc2.Clear(); + loc3.Clear(); + tables.AddRange(loc1); + } + return tables; + } - public List GetEnumsByDatabase(params string[] database) { - if (database == null || database.Length == 0) return new List(); - var drs = _orm.Ado.Query<(string name, string label)>(CommandType.Text, _commonUtils.FormatSql(@" + public List GetEnumsByDatabase(params string[] database) + { + if (database == null || database.Length == 0) return new List(); + var drs = _orm.Ado.Query<(string name, string label)>(CommandType.Text, _commonUtils.FormatSql(@" select ns.nspname || '.' || a.typname, b.enumlabel @@ -508,15 +541,16 @@ from pg_type a inner join pg_enum b on b.enumtypid = a.oid inner join pg_namespace ns on ns.oid = a.typnamespace where a.typtype = 'e' and ns.nspname in (SELECT ""schema_name"" FROM information_schema.schemata where catalog_name in {0})", database)); - var ret = new Dictionary>(); - foreach (var dr in drs) { - if (ret.TryGetValue(dr.name, out var labels) == false) ret.Add(dr.name, labels = new Dictionary()); - var key = dr.label; - if (Regex.IsMatch(key, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$") == false) - key = $"Unkown{ret[dr.name].Count + 1}"; - if (labels.ContainsKey(key) == false) labels.Add(key, dr.label); - } - return ret.Select(a => new DbEnumInfo { Name = a.Key, Labels = a.Value }).ToList(); - } - } + var ret = new Dictionary>(); + foreach (var dr in drs) + { + if (ret.TryGetValue(dr.name, out var labels) == false) ret.Add(dr.name, labels = new Dictionary()); + var key = dr.label; + if (Regex.IsMatch(key, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$") == false) + key = $"Unkown{ret[dr.name].Count + 1}"; + if (labels.ContainsKey(key) == false) labels.Add(key, dr.label); + } + return ret.Select(a => new DbEnumInfo { Name = a.Key, Labels = a.Value }).ToList(); + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs index cc3af126..28f59721 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExpression.cs @@ -8,491 +8,557 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.PostgreSQL { - class PostgreSQLExpression : CommonExpression { +namespace FreeSql.PostgreSQL +{ + class PostgreSQLExpression : CommonExpression + { - public PostgreSQLExpression(CommonUtils common) : base(common) { } + public PostgreSQLExpression(CommonUtils common) : base(common) { } - public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.NodeType) { - case ExpressionType.Convert: - var operandExp = (exp as UnaryExpression)?.Operand; - var gentype = exp.Type.NullableTypeOrThis(); - if (gentype != operandExp.Type.NullableTypeOrThis()) { - switch (exp.Type.NullableTypeOrThis().ToString()) { - case "System.Boolean": return $"(({getExp(operandExp)})::varchar not in ('0','false','f','no'))"; - case "System.Byte": return $"({getExp(operandExp)})::int2"; - case "System.Char": return $"substr(({getExp(operandExp)})::char, 1, 1)"; - case "System.DateTime": return $"({getExp(operandExp)})::timestamp"; - case "System.Decimal": return $"({getExp(operandExp)})::numeric"; - case "System.Double": return $"({getExp(operandExp)})::float8"; - case "System.Int16": return $"({getExp(operandExp)})::int2"; - case "System.Int32": return $"({getExp(operandExp)})::int4"; - case "System.Int64": return $"({getExp(operandExp)})::int8"; - case "System.SByte": return $"({getExp(operandExp)})::int2"; - case "System.Single": return $"({getExp(operandExp)})::float4"; - case "System.String": return $"({getExp(operandExp)})::varchar"; - case "System.UInt16": return $"({getExp(operandExp)})::int2"; - case "System.UInt32": return $"({getExp(operandExp)})::int4"; - case "System.UInt64": return $"({getExp(operandExp)})::int8"; - case "System.Guid": return $"({getExp(operandExp)})::uuid"; - } - } - break; - case ExpressionType.ArrayLength: - var arrOperExp = getExp((exp as UnaryExpression).Operand); - if (arrOperExp.StartsWith("(") || arrOperExp.EndsWith(")")) return $"array_length(array[{arrOperExp.TrimStart('(').TrimEnd(')')}],1)"; - return $"case when {arrOperExp} is null then 0 else array_length({arrOperExp},1) end"; - case ExpressionType.Call: - var callExp = exp as MethodCallExpression; + public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.NodeType) + { + case ExpressionType.Convert: + var operandExp = (exp as UnaryExpression)?.Operand; + var gentype = exp.Type.NullableTypeOrThis(); + if (gentype != operandExp.Type.NullableTypeOrThis()) + { + switch (exp.Type.NullableTypeOrThis().ToString()) + { + case "System.Boolean": return $"(({getExp(operandExp)})::varchar not in ('0','false','f','no'))"; + case "System.Byte": return $"({getExp(operandExp)})::int2"; + case "System.Char": return $"substr(({getExp(operandExp)})::char, 1, 1)"; + case "System.DateTime": return $"({getExp(operandExp)})::timestamp"; + case "System.Decimal": return $"({getExp(operandExp)})::numeric"; + case "System.Double": return $"({getExp(operandExp)})::float8"; + case "System.Int16": return $"({getExp(operandExp)})::int2"; + case "System.Int32": return $"({getExp(operandExp)})::int4"; + case "System.Int64": return $"({getExp(operandExp)})::int8"; + case "System.SByte": return $"({getExp(operandExp)})::int2"; + case "System.Single": return $"({getExp(operandExp)})::float4"; + case "System.String": return $"({getExp(operandExp)})::varchar"; + case "System.UInt16": return $"({getExp(operandExp)})::int2"; + case "System.UInt32": return $"({getExp(operandExp)})::int4"; + case "System.UInt64": return $"({getExp(operandExp)})::int8"; + case "System.Guid": return $"({getExp(operandExp)})::uuid"; + } + } + break; + case ExpressionType.ArrayLength: + var arrOperExp = getExp((exp as UnaryExpression).Operand); + if (arrOperExp.StartsWith("(") || arrOperExp.EndsWith(")")) return $"array_length(array[{arrOperExp.TrimStart('(').TrimEnd(')')}],1)"; + return $"case when {arrOperExp} is null then 0 else array_length({arrOperExp},1) end"; + case ExpressionType.Call: + var callExp = exp as MethodCallExpression; - switch (callExp.Method.Name) { - case "Parse": - case "TryParse": - switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) { - case "System.Boolean": return $"(({getExp(callExp.Arguments[0])})::varchar not in ('0','false','f','no'))"; - case "System.Byte": return $"({getExp(callExp.Arguments[0])})::int2"; - case "System.Char": return $"substr(({getExp(callExp.Arguments[0])})::char, 1, 1)"; - case "System.DateTime": return $"({getExp(callExp.Arguments[0])})::timestamp"; - case "System.Decimal": return $"({getExp(callExp.Arguments[0])})::numeric"; - case "System.Double": return $"({getExp(callExp.Arguments[0])})::float8"; - case "System.Int16": return $"({getExp(callExp.Arguments[0])})::int2"; - case "System.Int32": return $"({getExp(callExp.Arguments[0])})::int4"; - case "System.Int64": return $"({getExp(callExp.Arguments[0])})::int8"; - case "System.SByte": return $"({getExp(callExp.Arguments[0])})::int2"; - case "System.Single": return $"({getExp(callExp.Arguments[0])})::float4"; - case "System.UInt16": return $"({getExp(callExp.Arguments[0])})::int2"; - case "System.UInt32": return $"({getExp(callExp.Arguments[0])})::int4"; - case "System.UInt64": return $"({getExp(callExp.Arguments[0])})::int8"; - case "System.Guid": return $"({getExp(callExp.Arguments[0])})::uuid"; - } - break; - case "NewGuid": - break; - case "Next": - if (callExp.Object?.Type == typeof(Random)) return "(random()*1000000000)::int4"; - break; - case "NextDouble": - if (callExp.Object?.Type == typeof(Random)) return "random()"; - break; - case "Random": - if (callExp.Method.DeclaringType.IsNumberType()) return "random()"; - break; - case "ToString": - if (callExp.Object != null) return $"({getExp(callExp.Object)})::varchar"; - break; - } + switch (callExp.Method.Name) + { + case "Parse": + case "TryParse": + switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) + { + case "System.Boolean": return $"(({getExp(callExp.Arguments[0])})::varchar not in ('0','false','f','no'))"; + case "System.Byte": return $"({getExp(callExp.Arguments[0])})::int2"; + case "System.Char": return $"substr(({getExp(callExp.Arguments[0])})::char, 1, 1)"; + case "System.DateTime": return $"({getExp(callExp.Arguments[0])})::timestamp"; + case "System.Decimal": return $"({getExp(callExp.Arguments[0])})::numeric"; + case "System.Double": return $"({getExp(callExp.Arguments[0])})::float8"; + case "System.Int16": return $"({getExp(callExp.Arguments[0])})::int2"; + case "System.Int32": return $"({getExp(callExp.Arguments[0])})::int4"; + case "System.Int64": return $"({getExp(callExp.Arguments[0])})::int8"; + case "System.SByte": return $"({getExp(callExp.Arguments[0])})::int2"; + case "System.Single": return $"({getExp(callExp.Arguments[0])})::float4"; + case "System.UInt16": return $"({getExp(callExp.Arguments[0])})::int2"; + case "System.UInt32": return $"({getExp(callExp.Arguments[0])})::int4"; + case "System.UInt64": return $"({getExp(callExp.Arguments[0])})::int8"; + case "System.Guid": return $"({getExp(callExp.Arguments[0])})::uuid"; + } + break; + case "NewGuid": + break; + case "Next": + if (callExp.Object?.Type == typeof(Random)) return "(random()*1000000000)::int4"; + break; + case "NextDouble": + if (callExp.Object?.Type == typeof(Random)) return "random()"; + break; + case "Random": + if (callExp.Method.DeclaringType.IsNumberType()) return "random()"; + break; + case "ToString": + if (callExp.Object != null) return $"({getExp(callExp.Object)})::varchar"; + break; + } - var objExp = callExp.Object; - var objType = objExp?.Type; - if (objType?.FullName == "System.Byte[]") return null; + var objExp = callExp.Object; + var objType = objExp?.Type; + if (objType?.FullName == "System.Byte[]") return null; - var argIndex = 0; - if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) { - objExp = callExp.Arguments.FirstOrDefault(); - objType = objExp?.Type; - argIndex++; - } - if (objType == null) objType = callExp.Method.DeclaringType; - if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) { - var left = objExp == null ? null : getExp(objExp); - switch (objType.FullName) { - case "Newtonsoft.Json.Linq.JToken": - case "Newtonsoft.Json.Linq.JObject": - case "Newtonsoft.Json.Linq.JArray": - switch (callExp.Method.Name) { - case "Any": return $"(jsonb_array_length(coalesce({left},'[]')) > 0)"; - case "Contains": - var json = getExp(callExp.Arguments[argIndex]); - if (objType == typeof(JArray)) - return $"(coalesce({left},'[]') ? ({json})::varchar)"; - if (json.StartsWith("'") && json.EndsWith("'")) - return $"(coalesce({left},'{{}}') @> {_common.FormatSql("{0}", JToken.Parse(json.Trim('\'')))})"; - return $"(coalesce({left},'{{}}') @> ({json})::jsonb)"; - case "ContainsKey": return $"(coalesce({left},'{{}}') ? {getExp(callExp.Arguments[argIndex])})"; - case "Concat": - var right2 = getExp(callExp.Arguments[argIndex]); - return $"(coalesce({left},'{{}}') || {right2})"; - case "LongCount": - case "Count": return $"jsonb_array_length(coalesce({left},'[]'))"; - case "Parse": - var json2 = getExp(callExp.Arguments[argIndex]); - if (json2.StartsWith("'") && json2.EndsWith("'")) return _common.FormatSql("{0}", JToken.Parse(json2.Trim('\''))); - return $"({json2})::jsonb"; - } - break; - } - if (objType.FullName == typeof(Dictionary).FullName) { - switch (callExp.Method.Name) { - case "Contains": - var right = getExp(callExp.Arguments[argIndex]); - return $"({left} @> ({right}))"; - case "ContainsKey": return $"({left} ? {getExp(callExp.Arguments[argIndex])})"; - case "Concat": return $"({left} || {getExp(callExp.Arguments[argIndex])})"; - case "GetLength": - case "GetLongLength": - case "Count": return $"case when {left} is null then 0 else array_length(akeys({left}),1) end"; - case "Keys": return $"akeys({left})"; - case "Values": return $"avals({left})"; - } - } - switch (callExp.Method.Name) { - case "Any": - if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; - return $"(case when {left} is null then 0 else array_length({left},1) end > 0)"; - case "Contains": - //判断 in 或 array @> array - var right1 = getExp(callExp.Arguments[argIndex]); - if (left.StartsWith("array[") || left.EndsWith("]")) - return $"{right1} in ({left.Substring(6, left.Length - 7)})"; - if (left.StartsWith("(") || left.EndsWith(")")) - return $"{right1} in {left}"; - if (right1.StartsWith("(") || right1.EndsWith(")")) right1 = $"array[{right1.TrimStart('(').TrimEnd(')')}]"; - return $"({left} @> array[{right1}])"; - case "Concat": - if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; - var right2 = getExp(callExp.Arguments[argIndex]); - if (right2.StartsWith("(") || right2.EndsWith(")")) right2 = $"array[{right2.TrimStart('(').TrimEnd(')')}]"; - return $"({left} || {right2})"; - case "GetLength": - case "GetLongLength": - case "Length": - case "Count": - if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; - return $"case when {left} is null then 0 else array_length({left},1) end"; - } - } - break; - case ExpressionType.MemberAccess: - var memExp = exp as MemberExpression; - var memParentExp = memExp.Expression?.Type; - if (memParentExp?.FullName == "System.Byte[]") return null; - if (memParentExp != null) { - if (memParentExp.IsArray == true) { - var left = getExp(memExp.Expression); - if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; - switch (memExp.Member.Name) { - case "Length": - case "Count": return $"case when {left} is null then 0 else array_length({left},1) end"; - } - } - switch (memParentExp.FullName) { - case "Newtonsoft.Json.Linq.JToken": - case "Newtonsoft.Json.Linq.JObject": - case "Newtonsoft.Json.Linq.JArray": - var left = getExp(memExp.Expression); - switch (memExp.Member.Name) { - case "Count": return $"jsonb_array_length(coalesce({left},'[]'))"; - } - break; - } - if (memParentExp.FullName == typeof(Dictionary).FullName) { - var left = getExp(memExp.Expression); - switch (memExp.Member.Name) { - case "Count": return $"case when {left} is null then 0 else array_length(akeys({left}),1) end"; - case "Keys": return $"akeys({left})"; - case "Values": return $"avals({left})"; - } - } - } - break; - case ExpressionType.NewArrayInit: - var arrExp = exp as NewArrayExpression; - var arrSb = new StringBuilder(); - arrSb.Append("array["); - for (var a = 0; a < arrExp.Expressions.Count; a++) { - if (a > 0) arrSb.Append(","); - arrSb.Append(getExp(arrExp.Expressions[a])); - } - if (arrSb.Length == 1) arrSb.Append("NULL"); - return arrSb.Append("]").ToString(); - case ExpressionType.ListInit: - var listExp = exp as ListInitExpression; - var listSb = new StringBuilder(); - listSb.Append("("); - for (var a = 0; a < listExp.Initializers.Count; a++) { - if (listExp.Initializers[a].Arguments.Any() == false) continue; - if (a > 0) listSb.Append(","); - listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); - } - if (listSb.Length == 1) listSb.Append("NULL"); - return listSb.Append(")").ToString(); - case ExpressionType.New: - var newExp = exp as NewExpression; - if (typeof(IList).IsAssignableFrom(newExp.Type)) { - if (newExp.Arguments.Count == 0) return "(NULL)"; - if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; - return getExp(newExp.Arguments[0]); - } - return null; - } - return null; - } + var argIndex = 0; + if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) + { + objExp = callExp.Arguments.FirstOrDefault(); + objType = objExp?.Type; + argIndex++; + } + if (objType == null) objType = callExp.Method.DeclaringType; + if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) + { + var left = objExp == null ? null : getExp(objExp); + switch (objType.FullName) + { + case "Newtonsoft.Json.Linq.JToken": + case "Newtonsoft.Json.Linq.JObject": + case "Newtonsoft.Json.Linq.JArray": + switch (callExp.Method.Name) + { + case "Any": return $"(jsonb_array_length(coalesce({left},'[]')) > 0)"; + case "Contains": + var json = getExp(callExp.Arguments[argIndex]); + if (objType == typeof(JArray)) + return $"(coalesce({left},'[]') ? ({json})::varchar)"; + if (json.StartsWith("'") && json.EndsWith("'")) + return $"(coalesce({left},'{{}}') @> {_common.FormatSql("{0}", JToken.Parse(json.Trim('\'')))})"; + return $"(coalesce({left},'{{}}') @> ({json})::jsonb)"; + case "ContainsKey": return $"(coalesce({left},'{{}}') ? {getExp(callExp.Arguments[argIndex])})"; + case "Concat": + var right2 = getExp(callExp.Arguments[argIndex]); + return $"(coalesce({left},'{{}}') || {right2})"; + case "LongCount": + case "Count": return $"jsonb_array_length(coalesce({left},'[]'))"; + case "Parse": + var json2 = getExp(callExp.Arguments[argIndex]); + if (json2.StartsWith("'") && json2.EndsWith("'")) return _common.FormatSql("{0}", JToken.Parse(json2.Trim('\''))); + return $"({json2})::jsonb"; + } + break; + } + if (objType.FullName == typeof(Dictionary).FullName) + { + switch (callExp.Method.Name) + { + case "Contains": + var right = getExp(callExp.Arguments[argIndex]); + return $"({left} @> ({right}))"; + case "ContainsKey": return $"({left} ? {getExp(callExp.Arguments[argIndex])})"; + case "Concat": return $"({left} || {getExp(callExp.Arguments[argIndex])})"; + case "GetLength": + case "GetLongLength": + case "Count": return $"case when {left} is null then 0 else array_length(akeys({left}),1) end"; + case "Keys": return $"akeys({left})"; + case "Values": return $"avals({left})"; + } + } + switch (callExp.Method.Name) + { + case "Any": + if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; + return $"(case when {left} is null then 0 else array_length({left},1) end > 0)"; + case "Contains": + //判断 in 或 array @> array + var right1 = getExp(callExp.Arguments[argIndex]); + if (left.StartsWith("array[") || left.EndsWith("]")) + return $"{right1} in ({left.Substring(6, left.Length - 7)})"; + if (left.StartsWith("(") || left.EndsWith(")")) + return $"{right1} in {left}"; + if (right1.StartsWith("(") || right1.EndsWith(")")) right1 = $"array[{right1.TrimStart('(').TrimEnd(')')}]"; + return $"({left} @> array[{right1}])"; + case "Concat": + if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; + var right2 = getExp(callExp.Arguments[argIndex]); + if (right2.StartsWith("(") || right2.EndsWith(")")) right2 = $"array[{right2.TrimStart('(').TrimEnd(')')}]"; + return $"({left} || {right2})"; + case "GetLength": + case "GetLongLength": + case "Length": + case "Count": + if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; + return $"case when {left} is null then 0 else array_length({left},1) end"; + } + } + break; + case ExpressionType.MemberAccess: + var memExp = exp as MemberExpression; + var memParentExp = memExp.Expression?.Type; + if (memParentExp?.FullName == "System.Byte[]") return null; + if (memParentExp != null) + { + if (memParentExp.IsArray == true) + { + var left = getExp(memExp.Expression); + if (left.StartsWith("(") || left.EndsWith(")")) left = $"array[{left.TrimStart('(').TrimEnd(')')}]"; + switch (memExp.Member.Name) + { + case "Length": + case "Count": return $"case when {left} is null then 0 else array_length({left},1) end"; + } + } + switch (memParentExp.FullName) + { + case "Newtonsoft.Json.Linq.JToken": + case "Newtonsoft.Json.Linq.JObject": + case "Newtonsoft.Json.Linq.JArray": + var left = getExp(memExp.Expression); + switch (memExp.Member.Name) + { + case "Count": return $"jsonb_array_length(coalesce({left},'[]'))"; + } + break; + } + if (memParentExp.FullName == typeof(Dictionary).FullName) + { + var left = getExp(memExp.Expression); + switch (memExp.Member.Name) + { + case "Count": return $"case when {left} is null then 0 else array_length(akeys({left}),1) end"; + case "Keys": return $"akeys({left})"; + case "Values": return $"avals({left})"; + } + } + } + break; + case ExpressionType.NewArrayInit: + var arrExp = exp as NewArrayExpression; + var arrSb = new StringBuilder(); + arrSb.Append("array["); + for (var a = 0; a < arrExp.Expressions.Count; a++) + { + if (a > 0) arrSb.Append(","); + arrSb.Append(getExp(arrExp.Expressions[a])); + } + if (arrSb.Length == 1) arrSb.Append("NULL"); + return arrSb.Append("]").ToString(); + case ExpressionType.ListInit: + var listExp = exp as ListInitExpression; + var listSb = new StringBuilder(); + listSb.Append("("); + for (var a = 0; a < listExp.Initializers.Count; a++) + { + if (listExp.Initializers[a].Arguments.Any() == false) continue; + if (a > 0) listSb.Append(","); + listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); + } + if (listSb.Length == 1) listSb.Append("NULL"); + return listSb.Append(")").ToString(); + case ExpressionType.New: + var newExp = exp as NewExpression; + if (typeof(IList).IsAssignableFrom(newExp.Type)) + { + if (newExp.Arguments.Count == 0) return "(NULL)"; + if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; + return getExp(newExp.Arguments[0]); + } + return null; + } + return null; + } - public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Empty": return "''"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Length": return $"char_length({left})"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Now": return "current_timestamp"; - case "UtcNow": return "(current_timestamp at time zone 'UTC')"; - case "Today": return "current_date"; - case "MinValue": return "'0001/1/1 0:00:00'::timestamp"; - case "MaxValue": return "'9999/12/31 23:59:59'::timestamp"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Date": return $"({left})::date"; - case "TimeOfDay": return $"(extract(epoch from ({left})::time)*1000000)"; - case "DayOfWeek": return $"extract(dow from ({left})::timestamp)"; - case "Day": return $"extract(day from ({left})::timestamp)"; - case "DayOfYear": return $"extract(doy from ({left})::timestamp)"; - case "Month": return $"extract(month from ({left})::timestamp)"; - case "Year": return $"extract(year from ({left})::timestamp)"; - case "Hour": return $"extract(hour from ({left})::timestamp)"; - case "Minute": return $"extract(minute from ({left})::timestamp)"; - case "Second": return $"extract(second from ({left})::timestamp)"; - case "Millisecond": return $"(extract(milliseconds from ({left})::timestamp)-extract(second from ({left})::timestamp)*1000)"; - case "Ticks": return $"(extract(epoch from ({left})::timestamp)*10000000+621355968000000000)"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Zero": return "0"; - case "MinValue": return "-922337203685477580"; //微秒 Ticks / 10 - case "MaxValue": return "922337203685477580"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Days": return $"floor(({left})/{(long)1000000 * 60 * 60 * 24})"; - case "Hours": return $"floor(({left})/{(long)1000000 * 60 * 60}%24)"; - case "Milliseconds": return $"(floor(({left})/1000)::int8%1000)"; - case "Minutes": return $"(floor(({left})/{(long)1000000 * 60})::int8%60)"; - case "Seconds": return $"(floor(({left})/1000000)::int8%60)"; - case "Ticks": return $"(({left})*10)"; - case "TotalDays": return $"(({left})/{(long)1000000 * 60 * 60 * 24})"; - case "TotalHours": return $"(({left})/{(long)1000000 * 60 * 60})"; - case "TotalMilliseconds": return $"(({left})/1000)"; - case "TotalMinutes": return $"(({left})/{(long)1000000 * 60})"; - case "TotalSeconds": return $"(({left})/1000000)"; - } - return null; - } + public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Empty": return "''"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Length": return $"char_length({left})"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Now": return "current_timestamp"; + case "UtcNow": return "(current_timestamp at time zone 'UTC')"; + case "Today": return "current_date"; + case "MinValue": return "'0001/1/1 0:00:00'::timestamp"; + case "MaxValue": return "'9999/12/31 23:59:59'::timestamp"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Date": return $"({left})::date"; + case "TimeOfDay": return $"(extract(epoch from ({left})::time)*1000000)"; + case "DayOfWeek": return $"extract(dow from ({left})::timestamp)"; + case "Day": return $"extract(day from ({left})::timestamp)"; + case "DayOfYear": return $"extract(doy from ({left})::timestamp)"; + case "Month": return $"extract(month from ({left})::timestamp)"; + case "Year": return $"extract(year from ({left})::timestamp)"; + case "Hour": return $"extract(hour from ({left})::timestamp)"; + case "Minute": return $"extract(minute from ({left})::timestamp)"; + case "Second": return $"extract(second from ({left})::timestamp)"; + case "Millisecond": return $"(extract(milliseconds from ({left})::timestamp)-extract(second from ({left})::timestamp)*1000)"; + case "Ticks": return $"(extract(epoch from ({left})::timestamp)*10000000+621355968000000000)"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Zero": return "0"; + case "MinValue": return "-922337203685477580"; //微秒 Ticks / 10 + case "MaxValue": return "922337203685477580"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Days": return $"floor(({left})/{(long)1000000 * 60 * 60 * 24})"; + case "Hours": return $"floor(({left})/{(long)1000000 * 60 * 60}%24)"; + case "Milliseconds": return $"(floor(({left})/1000)::int8%1000)"; + case "Minutes": return $"(floor(({left})/{(long)1000000 * 60})::int8%60)"; + case "Seconds": return $"(floor(({left})/1000000)::int8%60)"; + case "Ticks": return $"(({left})*10)"; + case "TotalDays": return $"(({left})/{(long)1000000 * 60 * 60 * 24})"; + case "TotalHours": return $"(({left})/{(long)1000000 * 60 * 60})"; + case "TotalMilliseconds": return $"(({left})/1000)"; + case "TotalMinutes": return $"(({left})/{(long)1000000 * 60})"; + case "TotalSeconds": return $"(({left})/1000000)"; + } + return null; + } - public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "IsNullOrEmpty": - var arg1 = getExp(exp.Arguments[0]); - return $"({arg1} is null or {arg1} = '')"; - case "Concat": - return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); - } - } else { - var left = getExp(exp.Object); - switch (exp.Method.Name) { - case "StartsWith": - case "EndsWith": - case "Contains": - var args0Value = getExp(exp.Arguments[0]); - if (args0Value == "NULL") return $"({left}) IS NULL"; - var likeOpt = "LIKE"; - if (exp.Arguments.Count > 1) { - if (exp.Arguments[1].Type == typeof(bool) || - exp.Arguments[1].Type == typeof(StringComparison) && getExp(exp.Arguments[0]).Contains("IgnoreCase")) likeOpt = "ILIKE"; - } - if (exp.Method.Name == "StartsWith") return $"({left}) {likeOpt} {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(({args0Value})::varchar || '%')")}"; - if (exp.Method.Name == "EndsWith") return $"({left}) {likeOpt} {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%' || ({args0Value})::varchar)")}"; - if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) {likeOpt} {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; - return $"({left}) {likeOpt} ('%' || ({args0Value})::varchar || '%')"; - case "ToLower": return $"lower({left})"; - case "ToUpper": return $"upper({left})"; - case "Substring": - var substrArgs1 = getExp(exp.Arguments[0]); - if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); - else substrArgs1 += "+1"; - if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; - return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; - case "IndexOf": return $"(strpos({left}, {getExp(exp.Arguments[0])})-1)"; - case "PadLeft": - if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})"; - return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "PadRight": - if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})"; - return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Trim": - case "TrimStart": - case "TrimEnd": - if (exp.Arguments.Count == 0) { - if (exp.Method.Name == "Trim") return $"trim({left})"; - if (exp.Method.Name == "TrimStart") return $"ltrim({left})"; - if (exp.Method.Name == "TrimEnd") return $"rtrim({left})"; - } - var trimArg1 = ""; - var trimArg2 = ""; - foreach (var argsTrim02 in exp.Arguments) { - var argsTrim01s = new[] { argsTrim02 }; - if (argsTrim02.NodeType == ExpressionType.NewArrayInit) { - var arritem = argsTrim02 as NewArrayExpression; - argsTrim01s = arritem.Expressions.ToArray(); - } - foreach (var argsTrim01 in argsTrim01s) { - var trimChr = getExp(argsTrim01).Trim('\''); - if (trimChr.Length == 1) trimArg1 += trimChr; - else trimArg2 += $" || ({trimChr})"; - } - } - if (exp.Method.Name == "Trim") left = $"trim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; - if (exp.Method.Name == "TrimStart") left = $"ltrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; - if (exp.Method.Name == "TrimEnd") left = $"rtrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; - return left; - case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "CompareTo": return $"case when {left} = {getExp(exp.Arguments[0])} then 0 when {left} > {getExp(exp.Arguments[0])} then 1 else -1 end"; - case "Equals": return $"({left} = ({getExp(exp.Arguments[0])})::varchar)"; - } - } - throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.Method.Name) { - case "Abs": return $"abs({getExp(exp.Arguments[0])})"; - case "Sign": return $"sign({getExp(exp.Arguments[0])})"; - case "Floor": return $"floor({getExp(exp.Arguments[0])})"; - case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})"; - case "Round": - if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - return $"round({getExp(exp.Arguments[0])})"; - case "Exp": return $"exp({getExp(exp.Arguments[0])})"; - case "Log": return $"log({getExp(exp.Arguments[0])})"; - case "Log10": return $"log10({getExp(exp.Arguments[0])})"; - case "Pow": return $"pow({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; - case "Cos": return $"cos({getExp(exp.Arguments[0])})"; - case "Sin": return $"sin({getExp(exp.Arguments[0])})"; - case "Tan": return $"tan({getExp(exp.Arguments[0])})"; - case "Acos": return $"acos({getExp(exp.Arguments[0])})"; - case "Asin": return $"asin({getExp(exp.Arguments[0])})"; - case "Atan": return $"atan({getExp(exp.Arguments[0])})"; - case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Truncate": return $"trunc({getExp(exp.Arguments[0])}, 0)"; - } - throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"extract(epoch from ({getExp(exp.Arguments[0])})::timestamp-({getExp(exp.Arguments[1])})::timestamp)"; - case "DaysInMonth": return $"extract(day from ({getExp(exp.Arguments[0])} || '-' || {getExp(exp.Arguments[1])} || '-01')::timestamp+'1 month'::interval-'1 day'::interval)"; - case "Equals": return $"(({getExp(exp.Arguments[0])})::timestamp = ({getExp(exp.Arguments[1])})::timestamp)"; + public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "IsNullOrEmpty": + var arg1 = getExp(exp.Arguments[0]); + return $"({arg1} is null or {arg1} = '')"; + case "Concat": + return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); + } + } + else + { + var left = getExp(exp.Object); + switch (exp.Method.Name) + { + case "StartsWith": + case "EndsWith": + case "Contains": + var args0Value = getExp(exp.Arguments[0]); + if (args0Value == "NULL") return $"({left}) IS NULL"; + var likeOpt = "LIKE"; + if (exp.Arguments.Count > 1) + { + if (exp.Arguments[1].Type == typeof(bool) || + exp.Arguments[1].Type == typeof(StringComparison) && getExp(exp.Arguments[0]).Contains("IgnoreCase")) likeOpt = "ILIKE"; + } + if (exp.Method.Name == "StartsWith") return $"({left}) {likeOpt} {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(({args0Value})::varchar || '%')")}"; + if (exp.Method.Name == "EndsWith") return $"({left}) {likeOpt} {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%' || ({args0Value})::varchar)")}"; + if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) {likeOpt} {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; + return $"({left}) {likeOpt} ('%' || ({args0Value})::varchar || '%')"; + case "ToLower": return $"lower({left})"; + case "ToUpper": return $"upper({left})"; + case "Substring": + var substrArgs1 = getExp(exp.Arguments[0]); + if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); + else substrArgs1 += "+1"; + if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; + return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; + case "IndexOf": return $"(strpos({left}, {getExp(exp.Arguments[0])})-1)"; + case "PadLeft": + if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})"; + return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "PadRight": + if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})"; + return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Trim": + case "TrimStart": + case "TrimEnd": + if (exp.Arguments.Count == 0) + { + if (exp.Method.Name == "Trim") return $"trim({left})"; + if (exp.Method.Name == "TrimStart") return $"ltrim({left})"; + if (exp.Method.Name == "TrimEnd") return $"rtrim({left})"; + } + var trimArg1 = ""; + var trimArg2 = ""; + foreach (var argsTrim02 in exp.Arguments) + { + var argsTrim01s = new[] { argsTrim02 }; + if (argsTrim02.NodeType == ExpressionType.NewArrayInit) + { + var arritem = argsTrim02 as NewArrayExpression; + argsTrim01s = arritem.Expressions.ToArray(); + } + foreach (var argsTrim01 in argsTrim01s) + { + var trimChr = getExp(argsTrim01).Trim('\''); + if (trimChr.Length == 1) trimArg1 += trimChr; + else trimArg2 += $" || ({trimChr})"; + } + } + if (exp.Method.Name == "Trim") left = $"trim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; + if (exp.Method.Name == "TrimStart") left = $"ltrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; + if (exp.Method.Name == "TrimEnd") left = $"rtrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; + return left; + case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "CompareTo": return $"case when {left} = {getExp(exp.Arguments[0])} then 0 when {left} > {getExp(exp.Arguments[0])} then 1 else -1 end"; + case "Equals": return $"({left} = ({getExp(exp.Arguments[0])})::varchar)"; + } + } + throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.Method.Name) + { + case "Abs": return $"abs({getExp(exp.Arguments[0])})"; + case "Sign": return $"sign({getExp(exp.Arguments[0])})"; + case "Floor": return $"floor({getExp(exp.Arguments[0])})"; + case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})"; + case "Round": + if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + return $"round({getExp(exp.Arguments[0])})"; + case "Exp": return $"exp({getExp(exp.Arguments[0])})"; + case "Log": return $"log({getExp(exp.Arguments[0])})"; + case "Log10": return $"log10({getExp(exp.Arguments[0])})"; + case "Pow": return $"pow({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; + case "Cos": return $"cos({getExp(exp.Arguments[0])})"; + case "Sin": return $"sin({getExp(exp.Arguments[0])})"; + case "Tan": return $"tan({getExp(exp.Arguments[0])})"; + case "Acos": return $"acos({getExp(exp.Arguments[0])})"; + case "Asin": return $"asin({getExp(exp.Arguments[0])})"; + case "Atan": return $"atan({getExp(exp.Arguments[0])})"; + case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Truncate": return $"trunc({getExp(exp.Arguments[0])}, 0)"; + } + throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"extract(epoch from ({getExp(exp.Arguments[0])})::timestamp-({getExp(exp.Arguments[1])})::timestamp)"; + case "DaysInMonth": return $"extract(day from ({getExp(exp.Arguments[0])} || '-' || {getExp(exp.Arguments[1])} || '-01')::timestamp+'1 month'::interval-'1 day'::interval)"; + case "Equals": return $"(({getExp(exp.Arguments[0])})::timestamp = ({getExp(exp.Arguments[1])})::timestamp)"; - case "IsLeapYear": - var isLeapYearArgs1 = getExp(exp.Arguments[0]); - return $"(({isLeapYearArgs1})::int8%4=0 AND ({isLeapYearArgs1})::int8%100<>0 OR ({isLeapYearArgs1})::int8%400=0)"; + case "IsLeapYear": + var isLeapYearArgs1 = getExp(exp.Arguments[0]); + return $"(({isLeapYearArgs1})::int8%4=0 AND ({isLeapYearArgs1})::int8%100<>0 OR ({isLeapYearArgs1})::int8%400=0)"; - case "Parse": return $"({getExp(exp.Arguments[0])})::timestamp"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"({getExp(exp.Arguments[0])})::timestamp"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"(({left})::timestamp+(({args1})||' microseconds')::interval)"; - case "AddDays": return $"(({left})::timestamp+(({args1})||' day')::interval)"; - case "AddHours": return $"(({left})::timestamp+(({args1})||' hour')::interval)"; - case "AddMilliseconds": return $"(({left})::timestamp+(({args1})||' milliseconds')::interval)"; - case "AddMinutes": return $"(({left})::timestamp+(({args1})||' minute')::interval)"; - case "AddMonths": return $"(({left})::timestamp+(({args1})||' month')::interval)"; - case "AddSeconds": return $"(({left})::timestamp+(({args1})||' second')::interval)"; - case "AddTicks": return $"(({left})::timestamp+(({args1})/10||' microseconds')::interval)"; - case "AddYears": return $"(({left})::timestamp+(({args1})||' year')::interval)"; - case "Subtract": - switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) { - case "System.DateTime": return $"(extract(epoch from ({left})::timestamp-({args1})::timestamp)*1000000)"; - case "System.TimeSpan": return $"(({left})::timestamp-(({args1})||' microseconds')::interval)"; - } - break; - case "Equals": return $"({left} = ({getExp(exp.Arguments[0])})::timestamp)"; - case "CompareTo": return $"extract(epoch from ({left})::timestamp-({getExp(exp.Arguments[0])})::timestamp)"; - case "ToString": return $"to_char({left}, 'YYYY-MM-DD HH24:MI:SS.US')"; - } - } - throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "FromDays": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60 * 24})"; - case "FromHours": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60})"; - case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})*1000)"; - case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60})"; - case "FromSeconds": return $"(({getExp(exp.Arguments[0])})*1000000)"; - case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10)"; - case "Parse": return $"({getExp(exp.Arguments[0])})::int8"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"({getExp(exp.Arguments[0])})::int8"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"({left}+{args1})"; - case "Subtract": return $"({left}-({args1}))"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))"; - case "ToString": return $"({left})::varchar"; - } - } - throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "ToBoolean": return $"(({getExp(exp.Arguments[0])})::varchar not in ('0','false','f','no'))"; - case "ToByte": return $"({getExp(exp.Arguments[0])})::int2"; - case "ToChar": return $"substr(({getExp(exp.Arguments[0])})::char, 1, 1)"; - case "ToDateTime": return $"({getExp(exp.Arguments[0])})::timestamp"; - case "ToDecimal": return $"({getExp(exp.Arguments[0])})::numeric"; - case "ToDouble": return $"({getExp(exp.Arguments[0])})::float8"; - case "ToInt16": return $"({getExp(exp.Arguments[0])})::int2"; - case "ToInt32": return $"({getExp(exp.Arguments[0])})::int4"; - case "ToInt64": return $"({getExp(exp.Arguments[0])})::int8"; - case "ToSByte": return $"({getExp(exp.Arguments[0])})::int2"; - case "ToSingle": return $"({getExp(exp.Arguments[0])})::float4"; - case "ToString": return $"({getExp(exp.Arguments[0])})::varchar"; - case "ToUInt16": return $"({getExp(exp.Arguments[0])})::int2"; - case "ToUInt32": return $"({getExp(exp.Arguments[0])})::int4"; - case "ToUInt64": return $"({getExp(exp.Arguments[0])})::int8"; - } - } - throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); - } - } + case "Parse": return $"({getExp(exp.Arguments[0])})::timestamp"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"({getExp(exp.Arguments[0])})::timestamp"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"(({left})::timestamp+(({args1})||' microseconds')::interval)"; + case "AddDays": return $"(({left})::timestamp+(({args1})||' day')::interval)"; + case "AddHours": return $"(({left})::timestamp+(({args1})||' hour')::interval)"; + case "AddMilliseconds": return $"(({left})::timestamp+(({args1})||' milliseconds')::interval)"; + case "AddMinutes": return $"(({left})::timestamp+(({args1})||' minute')::interval)"; + case "AddMonths": return $"(({left})::timestamp+(({args1})||' month')::interval)"; + case "AddSeconds": return $"(({left})::timestamp+(({args1})||' second')::interval)"; + case "AddTicks": return $"(({left})::timestamp+(({args1})/10||' microseconds')::interval)"; + case "AddYears": return $"(({left})::timestamp+(({args1})||' year')::interval)"; + case "Subtract": + switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) + { + case "System.DateTime": return $"(extract(epoch from ({left})::timestamp-({args1})::timestamp)*1000000)"; + case "System.TimeSpan": return $"(({left})::timestamp-(({args1})||' microseconds')::interval)"; + } + break; + case "Equals": return $"({left} = ({getExp(exp.Arguments[0])})::timestamp)"; + case "CompareTo": return $"extract(epoch from ({left})::timestamp-({getExp(exp.Arguments[0])})::timestamp)"; + case "ToString": return $"to_char({left}, 'YYYY-MM-DD HH24:MI:SS.US')"; + } + } + throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + case "FromDays": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60 * 24})"; + case "FromHours": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60 * 60})"; + case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})*1000)"; + case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*{(long)1000000 * 60})"; + case "FromSeconds": return $"(({getExp(exp.Arguments[0])})*1000000)"; + case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10)"; + case "Parse": return $"({getExp(exp.Arguments[0])})::int8"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"({getExp(exp.Arguments[0])})::int8"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"({left}+{args1})"; + case "Subtract": return $"({left}-({args1}))"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))"; + case "ToString": return $"({left})::varchar"; + } + } + throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "ToBoolean": return $"(({getExp(exp.Arguments[0])})::varchar not in ('0','false','f','no'))"; + case "ToByte": return $"({getExp(exp.Arguments[0])})::int2"; + case "ToChar": return $"substr(({getExp(exp.Arguments[0])})::char, 1, 1)"; + case "ToDateTime": return $"({getExp(exp.Arguments[0])})::timestamp"; + case "ToDecimal": return $"({getExp(exp.Arguments[0])})::numeric"; + case "ToDouble": return $"({getExp(exp.Arguments[0])})::float8"; + case "ToInt16": return $"({getExp(exp.Arguments[0])})::int2"; + case "ToInt32": return $"({getExp(exp.Arguments[0])})::int4"; + case "ToInt64": return $"({getExp(exp.Arguments[0])})::int8"; + case "ToSByte": return $"({getExp(exp.Arguments[0])})::int2"; + case "ToSingle": return $"({getExp(exp.Arguments[0])})::float4"; + case "ToString": return $"({getExp(exp.Arguments[0])})::varchar"; + case "ToUInt16": return $"({getExp(exp.Arguments[0])})::int2"; + case "ToUInt32": return $"({getExp(exp.Arguments[0])})::int4"; + case "ToUInt64": return $"({getExp(exp.Arguments[0])})::int8"; + } + } + throw new Exception($"PostgreSQLExpression 未实现函数表达式 {exp} 解析"); + } + } } diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExtensions.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExtensions.cs index adba0afb..40c5af93 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExtensions.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLExtensions.cs @@ -1,11 +1,12 @@ -public static partial class FreeSqlGlobalExtensions { +public static partial class FreeSqlGlobalExtensions +{ - /// - /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 - /// - /// - /// - /// - public static string FormatPostgreSQL(this string that, params object[] args) => _postgresqlAdo.Addslashes(that, args); - static FreeSql.PostgreSQL.PostgreSQLAdo _postgresqlAdo = new FreeSql.PostgreSQL.PostgreSQLAdo(); + /// + /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 + /// + /// + /// + /// + public static string FormatPostgreSQL(this string that, params object[] args) => _postgresqlAdo.Addslashes(that, args); + static FreeSql.PostgreSQL.PostgreSQLAdo _postgresqlAdo = new FreeSql.PostgreSQL.PostgreSQLAdo(); } diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLProvider.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLProvider.cs index 7f73ee10..b3f949aa 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLProvider.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLProvider.cs @@ -12,93 +12,101 @@ using System.Linq.Expressions; using System.Net; using System.Net.NetworkInformation; -namespace FreeSql.PostgreSQL { +namespace FreeSql.PostgreSQL +{ - public class PostgreSQLProvider : IFreeSql { + public class PostgreSQLProvider : IFreeSql + { - static PostgreSQLProvider() { - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(BitArray)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlPoint)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlLine)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlLSeg)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlBox)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlPath)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlPolygon)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlCircle)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof((IPAddress Address, int Subnet))] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(IPAddress)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PhysicalAddress)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlRange)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlRange)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlRange)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlRange)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisPoint)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisLineString)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisPolygon)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisMultiPoint)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisMultiLineString)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisMultiPolygon)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisGeometry)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisGeometryCollection)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(Dictionary)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(JToken)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(JObject)] = true; - Utils.dicExecuteArrayRowReadClassOrTuple[typeof(JArray)] = true; + static PostgreSQLProvider() + { + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(BitArray)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlPoint)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlLine)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlLSeg)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlBox)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlPath)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlPolygon)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlCircle)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof((IPAddress Address, int Subnet))] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(IPAddress)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PhysicalAddress)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlRange)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlRange)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlRange)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(NpgsqlRange)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisPoint)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisLineString)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisPolygon)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisMultiPoint)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisMultiLineString)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisMultiPolygon)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisGeometry)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(PostgisGeometryCollection)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(Dictionary)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(JToken)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(JObject)] = true; + Utils.dicExecuteArrayRowReadClassOrTuple[typeof(JArray)] = true; - var MethodJTokenParse = typeof(JToken).GetMethod("Parse", new[] { typeof(string) }); - var MethodJObjectParse = typeof(JObject).GetMethod("Parse", new[] { typeof(string) }); - var MethodJArrayParse = typeof(JArray).GetMethod("Parse", new[] { typeof(string) }); - Utils.GetDataReaderValueBlockExpressionSwitchTypeFullName.Add((LabelTarget returnTarget, Expression valueExp, string typeFullName) => { - switch (typeFullName) { - case "Newtonsoft.Json.Linq.JToken": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodJTokenParse, Expression.Convert(valueExp, typeof(string))), typeof(JToken))); - case "Newtonsoft.Json.Linq.JObject": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodJObjectParse, Expression.Convert(valueExp, typeof(string))), typeof(JObject))); - case "Newtonsoft.Json.Linq.JArray": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodJArrayParse, Expression.Convert(valueExp, typeof(string))), typeof(JArray))); - case "Npgsql.LegacyPostgis.PostgisGeometry": return Expression.Return(returnTarget, valueExp); - } - return null; - }); - } + var MethodJTokenParse = typeof(JToken).GetMethod("Parse", new[] { typeof(string) }); + var MethodJObjectParse = typeof(JObject).GetMethod("Parse", new[] { typeof(string) }); + var MethodJArrayParse = typeof(JArray).GetMethod("Parse", new[] { typeof(string) }); + Utils.GetDataReaderValueBlockExpressionSwitchTypeFullName.Add((LabelTarget returnTarget, Expression valueExp, string typeFullName) => + { + switch (typeFullName) + { + case "Newtonsoft.Json.Linq.JToken": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodJTokenParse, Expression.Convert(valueExp, typeof(string))), typeof(JToken))); + case "Newtonsoft.Json.Linq.JObject": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodJObjectParse, Expression.Convert(valueExp, typeof(string))), typeof(JObject))); + case "Newtonsoft.Json.Linq.JArray": return Expression.Return(returnTarget, Expression.TypeAs(Expression.Call(MethodJArrayParse, Expression.Convert(valueExp, typeof(string))), typeof(JArray))); + case "Npgsql.LegacyPostgis.PostgisGeometry": return Expression.Return(returnTarget, valueExp); + } + return null; + }); + } - public ISelect Select() where T1 : class => new PostgreSQLSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public ISelect Select(object dywhere) where T1 : class => new PostgreSQLSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IInsert Insert() where T1 : class => new PostgreSQLInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); - public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); - public IUpdate Update() where T1 : class => new PostgreSQLUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IUpdate Update(object dywhere) where T1 : class => new PostgreSQLUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IDelete Delete() where T1 : class => new PostgreSQLDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IDelete Delete(object dywhere) where T1 : class => new PostgreSQLDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public ISelect Select() where T1 : class => new PostgreSQLSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public ISelect Select(object dywhere) where T1 : class => new PostgreSQLSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IInsert Insert() where T1 : class => new PostgreSQLInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); + public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); + public IUpdate Update() where T1 : class => new PostgreSQLUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IUpdate Update(object dywhere) where T1 : class => new PostgreSQLUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IDelete Delete() where T1 : class => new PostgreSQLDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IDelete Delete(object dywhere) where T1 : class => new PostgreSQLDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IAdo Ado { get; } - public IAop Aop { get; } - public ICodeFirst CodeFirst { get; } - public IDbFirst DbFirst { get; } - public PostgreSQLProvider(string masterConnectionString, string[] slaveConnectionString) { - this.InternalCommonUtils = new PostgreSQLUtils(this); - this.InternalCommonExpression = new PostgreSQLExpression(this.InternalCommonUtils); + public IAdo Ado { get; } + public IAop Aop { get; } + public ICodeFirst CodeFirst { get; } + public IDbFirst DbFirst { get; } + public PostgreSQLProvider(string masterConnectionString, string[] slaveConnectionString) + { + this.InternalCommonUtils = new PostgreSQLUtils(this); + this.InternalCommonExpression = new PostgreSQLExpression(this.InternalCommonUtils); - this.Ado = new PostgreSQLAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); - this.Aop = new AopProvider(); + this.Ado = new PostgreSQLAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); + this.Aop = new AopProvider(); - this.DbFirst = new PostgreSQLDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - this.CodeFirst = new PostgreSQLCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - } + this.DbFirst = new PostgreSQLDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + this.CodeFirst = new PostgreSQLCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + } - internal CommonUtils InternalCommonUtils { get; } - internal CommonExpression InternalCommonExpression { get; } + internal CommonUtils InternalCommonUtils { get; } + internal CommonExpression InternalCommonExpression { get; } - public void Transaction(Action handler) => Ado.Transaction(handler); + public void Transaction(Action handler) => Ado.Transaction(handler); - public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); + public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); - ~PostgreSQLProvider() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - (this.Ado as AdoProvider)?.Dispose(); - } - } + ~PostgreSQLProvider() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + (this.Ado as AdoProvider)?.Dispose(); + } + } } diff --git a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLUtils.cs b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLUtils.cs index 89817e27..3069d618 100644 --- a/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLUtils.cs +++ b/Providers/FreeSql.Provider.PostgreSQL/PostgreSQLUtils.cs @@ -14,157 +14,185 @@ using System.Text; using System.Linq.Expressions; using System.Reflection; -namespace FreeSql.PostgreSQL { +namespace FreeSql.PostgreSQL +{ - class PostgreSQLUtils : CommonUtils { - public PostgreSQLUtils(IFreeSql orm) : base(orm) { - } + class PostgreSQLUtils : CommonUtils + { + public PostgreSQLUtils(IFreeSql orm) : base(orm) + { + } - static Array getParamterArrayValue(Type arrayType, object value, object defaultValue) { - var valueArr = value as Array; - var len = valueArr.GetLength(0); - var ret = Array.CreateInstance(arrayType, len); - for (var a = 0; a < len; a++) { - var item = valueArr.GetValue(a); - ret.SetValue(item == null ? defaultValue : getParamterValue(item.GetType(), item, 1), a); - } - return ret; - } - static Dictionary> dicGetParamterValue = new Dictionary> { - { typeof(JToken).FullName, a => string.Concat(a) }, { typeof(JToken[]).FullName, a => getParamterArrayValue(typeof(string), a, null) }, - { typeof(JObject).FullName, a => string.Concat(a) }, { typeof(JObject[]).FullName, a => getParamterArrayValue(typeof(string), a, null) }, - { typeof(JArray).FullName, a => string.Concat(a) }, { typeof(JArray[]).FullName, a => getParamterArrayValue(typeof(string), a, null) }, - { typeof(uint).FullName, a => long.Parse(string.Concat(a)) }, { typeof(uint[]).FullName, a => getParamterArrayValue(typeof(long), a, 0) }, { typeof(uint?[]).FullName, a => getParamterArrayValue(typeof(long?), a, null) }, - { typeof(ulong).FullName, a => decimal.Parse(string.Concat(a)) }, { typeof(ulong[]).FullName, a => getParamterArrayValue(typeof(decimal), a, 0) }, { typeof(ulong?[]).FullName, a => getParamterArrayValue(typeof(decimal?), a, null) }, - { typeof(ushort).FullName, a => int.Parse(string.Concat(a)) }, { typeof(ushort[]).FullName, a => getParamterArrayValue(typeof(int), a, 0) }, { typeof(ushort?[]).FullName, a => getParamterArrayValue(typeof(int?), a, null) }, - { typeof(byte).FullName, a => short.Parse(string.Concat(a)) }, { typeof(byte[]).FullName, a => getParamterArrayValue(typeof(short), a, 0) }, { typeof(byte?[]).FullName, a => getParamterArrayValue(typeof(short?), a, null) }, - { typeof(sbyte).FullName, a => short.Parse(string.Concat(a)) }, { typeof(sbyte[]).FullName, a => getParamterArrayValue(typeof(short), a, 0) }, { typeof(sbyte?[]).FullName, a => getParamterArrayValue(typeof(short?), a, null) }, - { typeof(NpgsqlPath).FullName, a => { - var path = (NpgsqlPath)a; - try { int count = path.Count; return path; } catch { return new NpgsqlPath(new NpgsqlPoint(0, 0)); } - } }, { typeof(NpgsqlPath[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPath), a, new NpgsqlPath(new NpgsqlPoint(0, 0))) }, { typeof(NpgsqlPath?[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPath?), a, null) }, - { typeof(NpgsqlPolygon).FullName, a => { - var polygon = (NpgsqlPolygon)a; - try { int count = polygon.Count; return polygon; } catch { return new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0)); } - } }, { typeof(NpgsqlPolygon[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPolygon), a, new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0))) }, { typeof(NpgsqlPolygon?[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPolygon?), a, null) }, - { typeof((IPAddress Address, int Subnet)).FullName, a => { - var inet = ((IPAddress Address, int Subnet))a; - if (inet.Address == null) return (IPAddress.Any, inet.Subnet); - return inet; - } }, { typeof((IPAddress Address, int Subnet)[]).FullName, a => getParamterArrayValue(typeof((IPAddress Address, int Subnet)), a, (IPAddress.Any, 0)) }, { typeof((IPAddress Address, int Subnet)?[]).FullName, a => getParamterArrayValue(typeof((IPAddress Address, int Subnet)?), a, null) }, - }; - static object getParamterValue(Type type, object value, int level = 0) { - if (type.FullName == "System.Byte[]") return value; - if (type.IsArray && level == 0) { - var elementType = type.GetElementType(); - Type enumType = null; - if (elementType.IsEnum) enumType = elementType; - else if (elementType.IsNullableType() && elementType.GenericTypeArguments.First().IsEnum) enumType = elementType.GenericTypeArguments.First(); - if (enumType != null) return enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? - getParamterArrayValue(typeof(long), value, elementType.IsEnum ? null : Enum.GetValues(enumType).GetValue(0)) : - getParamterArrayValue(typeof(int), value, elementType.IsEnum ? null : Enum.GetValues(enumType).GetValue(0)); - return dicGetParamterValue.TryGetValue(type.FullName, out var trydicarr) ? trydicarr(value) : value; - } - if (type.IsNullableType()) type = type.GenericTypeArguments.First(); - if (type.IsEnum) return (int)value; - if (dicGetParamterValue.TryGetValue(type.FullName, out var trydic)) return trydic(value); - return value; - } + static Array getParamterArrayValue(Type arrayType, object value, object defaultValue) + { + var valueArr = value as Array; + var len = valueArr.GetLength(0); + var ret = Array.CreateInstance(arrayType, len); + for (var a = 0; a < len; a++) + { + var item = valueArr.GetValue(a); + ret.SetValue(item == null ? defaultValue : getParamterValue(item.GetType(), item, 1), a); + } + return ret; + } + static Dictionary> dicGetParamterValue = new Dictionary> { + { typeof(JToken).FullName, a => string.Concat(a) }, { typeof(JToken[]).FullName, a => getParamterArrayValue(typeof(string), a, null) }, + { typeof(JObject).FullName, a => string.Concat(a) }, { typeof(JObject[]).FullName, a => getParamterArrayValue(typeof(string), a, null) }, + { typeof(JArray).FullName, a => string.Concat(a) }, { typeof(JArray[]).FullName, a => getParamterArrayValue(typeof(string), a, null) }, + { typeof(uint).FullName, a => long.Parse(string.Concat(a)) }, { typeof(uint[]).FullName, a => getParamterArrayValue(typeof(long), a, 0) }, { typeof(uint?[]).FullName, a => getParamterArrayValue(typeof(long?), a, null) }, + { typeof(ulong).FullName, a => decimal.Parse(string.Concat(a)) }, { typeof(ulong[]).FullName, a => getParamterArrayValue(typeof(decimal), a, 0) }, { typeof(ulong?[]).FullName, a => getParamterArrayValue(typeof(decimal?), a, null) }, + { typeof(ushort).FullName, a => int.Parse(string.Concat(a)) }, { typeof(ushort[]).FullName, a => getParamterArrayValue(typeof(int), a, 0) }, { typeof(ushort?[]).FullName, a => getParamterArrayValue(typeof(int?), a, null) }, + { typeof(byte).FullName, a => short.Parse(string.Concat(a)) }, { typeof(byte[]).FullName, a => getParamterArrayValue(typeof(short), a, 0) }, { typeof(byte?[]).FullName, a => getParamterArrayValue(typeof(short?), a, null) }, + { typeof(sbyte).FullName, a => short.Parse(string.Concat(a)) }, { typeof(sbyte[]).FullName, a => getParamterArrayValue(typeof(short), a, 0) }, { typeof(sbyte?[]).FullName, a => getParamterArrayValue(typeof(short?), a, null) }, + { typeof(NpgsqlPath).FullName, a => { + var path = (NpgsqlPath)a; + try { int count = path.Count; return path; } catch { return new NpgsqlPath(new NpgsqlPoint(0, 0)); } + } }, { typeof(NpgsqlPath[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPath), a, new NpgsqlPath(new NpgsqlPoint(0, 0))) }, { typeof(NpgsqlPath?[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPath?), a, null) }, + { typeof(NpgsqlPolygon).FullName, a => { + var polygon = (NpgsqlPolygon)a; + try { int count = polygon.Count; return polygon; } catch { return new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0)); } + } }, { typeof(NpgsqlPolygon[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPolygon), a, new NpgsqlPolygon(new NpgsqlPoint(0, 0), new NpgsqlPoint(0, 0))) }, { typeof(NpgsqlPolygon?[]).FullName, a => getParamterArrayValue(typeof(NpgsqlPolygon?), a, null) }, + { typeof((IPAddress Address, int Subnet)).FullName, a => { + var inet = ((IPAddress Address, int Subnet))a; + if (inet.Address == null) return (IPAddress.Any, inet.Subnet); + return inet; + } }, { typeof((IPAddress Address, int Subnet)[]).FullName, a => getParamterArrayValue(typeof((IPAddress Address, int Subnet)), a, (IPAddress.Any, 0)) }, { typeof((IPAddress Address, int Subnet)?[]).FullName, a => getParamterArrayValue(typeof((IPAddress Address, int Subnet)?), a, null) }, + }; + static object getParamterValue(Type type, object value, int level = 0) + { + if (type.FullName == "System.Byte[]") return value; + if (type.IsArray && level == 0) + { + var elementType = type.GetElementType(); + Type enumType = null; + if (elementType.IsEnum) enumType = elementType; + else if (elementType.IsNullableType() && elementType.GenericTypeArguments.First().IsEnum) enumType = elementType.GenericTypeArguments.First(); + if (enumType != null) return enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? + getParamterArrayValue(typeof(long), value, elementType.IsEnum ? null : Enum.GetValues(enumType).GetValue(0)) : + getParamterArrayValue(typeof(int), value, elementType.IsEnum ? null : Enum.GetValues(enumType).GetValue(0)); + return dicGetParamterValue.TryGetValue(type.FullName, out var trydicarr) ? trydicarr(value) : value; + } + if (type.IsNullableType()) type = type.GenericTypeArguments.First(); + if (type.IsEnum) return (int)value; + if (dicGetParamterValue.TryGetValue(type.FullName, out var trydic)) return trydic(value); + return value; + } - public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) { - if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; - if (value != null) value = getParamterValue(type, value); - var ret = new NpgsqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; - //if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) { - // ret.DataTypeName = ""; - //} else { - var tp = _orm.CodeFirst.GetDbInfo(type)?.type; - if (tp != null) ret.NpgsqlDbType = (NpgsqlDbType)tp.Value; - //} - _params?.Add(ret); - return ret; - } + public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) + { + if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; + if (value != null) value = getParamterValue(type, value); + var ret = new NpgsqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; + //if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) { + // ret.DataTypeName = ""; + //} else { + var tp = _orm.CodeFirst.GetDbInfo(type)?.type; + if (tp != null) ret.NpgsqlDbType = (NpgsqlDbType)tp.Value; + //} + _params?.Add(ret); + return ret; + } - public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => - Utils.GetDbParamtersByObject(sql, obj, "@", (name, type, value) => { - if (value != null) value = getParamterValue(type, value); - var ret = new NpgsqlParameter { ParameterName = $"@{name}", Value = value }; - //if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) { - // ret.DataTypeName = ""; - //} else { - var tp = _orm.CodeFirst.GetDbInfo(type)?.type; - if (tp != null) ret.NpgsqlDbType = (NpgsqlDbType)tp.Value; - //} - return ret; - }); + public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => + Utils.GetDbParamtersByObject(sql, obj, "@", (name, type, value) => + { + if (value != null) value = getParamterValue(type, value); + var ret = new NpgsqlParameter { ParameterName = $"@{name}", Value = value }; + //if (value.GetType().IsEnum || value.GetType().GenericTypeArguments.FirstOrDefault()?.IsEnum == true) { + // ret.DataTypeName = ""; + //} else { + var tp = _orm.CodeFirst.GetDbInfo(type)?.type; + if (tp != null) ret.NpgsqlDbType = (NpgsqlDbType)tp.Value; + //} + return ret; + }); - public override string FormatSql(string sql, params object[] args) => sql?.FormatPostgreSQL(args); - public override string QuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"\"{nametrim.Trim('"').Replace(".", "\".\"")}\""; - } - public override string TrimQuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"{nametrim.Trim('"').Replace("\".\"", ".").Replace(".\"", ".")}"; - } - public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; - public override string IsNull(string sql, object value) => $"coalesce({sql}, {value})"; - public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; - public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; + public override string FormatSql(string sql, params object[] args) => sql?.FormatPostgreSQL(args); + public override string QuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"\"{nametrim.Trim('"').Replace(".", "\".\"")}\""; + } + public override string TrimQuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"{nametrim.Trim('"').Replace("\".\"", ".").Replace(".\"", ".")}"; + } + public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; + public override string IsNull(string sql, object value) => $"coalesce({sql}, {value})"; + public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; + public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; - public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; - public override string QuoteReadColumn(Type type, string columnName) => columnName; + public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; + public override string QuoteReadColumn(Type type, string columnName) => columnName; - static ConcurrentDictionary _dicIsAssignableFromPostgisGeometry = new ConcurrentDictionary(); - public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) { - if (value == null) return "NULL"; - if (_dicIsAssignableFromPostgisGeometry.GetOrAdd(type, t2 => typeof(PostgisGeometry).IsAssignableFrom(type.IsArray ? type.GetElementType() : type))) { - var pam = AppendParamter(specialParams, null, type, value); - return pam.ParameterName; - } - value = getParamterValue(type, value); - var type2 = value.GetType(); - if (type2 == typeof(byte[])) { - var bytes = value as byte[]; - var sb = new StringBuilder().Append("'\\x"); - foreach (var vc in bytes) { - if (vc < 10) sb.Append("0"); - sb.Append(vc.ToString("X")); - } - return sb.Append("'").ToString(); //val = Encoding.UTF8.GetString(val as byte[]); - } else if (type2 == typeof(TimeSpan) || type2 == typeof(TimeSpan?)) { - var ts = (TimeSpan)value; - return $"'{Math.Min(24, (int)Math.Floor(ts.TotalHours))}:{ts.Minutes}:{ts.Seconds}'"; - } else if (value is Array) { - var valueArr = value as Array; - var eleType = type2.GetElementType(); - var len = valueArr.GetLength(0); - var sb = new StringBuilder().Append("ARRAY["); - for (var a = 0; a < len; a++) { - var item = valueArr.GetValue(a); - if (a > 0) sb.Append(","); - sb.Append(GetNoneParamaterSqlValue(specialParams, eleType, item)); - } - sb.Append("]"); - var dbinfo = _orm.CodeFirst.GetDbInfo(type); - if (dbinfo.HasValue) sb.Append("::").Append(dbinfo.Value.dbtype); - return sb.ToString(); - } else if (type2 == typeof(BitArray)) { - return $"'{(value as BitArray).To1010()}'"; - } else if (type2 == typeof(NpgsqlLine) || type2 == typeof(NpgsqlLine?)) { - var line = value.ToString(); - return line == "{0,0,0}" ? "'{0,-1,-1}'" : $"'{line}'"; - } else if (type2 == typeof((IPAddress Address, int Subnet)) || type2 == typeof((IPAddress Address, int Subnet)?)) { - var cidr = ((IPAddress Address, int Subnet))value; - return $"'{cidr.Address}/{cidr.Subnet}'"; - } else if (dicGetParamterValue.ContainsKey(type2.FullName)) { - value = string.Concat(value); - } - return FormatSql("{0}", value, 1); - } - } + static ConcurrentDictionary _dicIsAssignableFromPostgisGeometry = new ConcurrentDictionary(); + public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) + { + if (value == null) return "NULL"; + if (_dicIsAssignableFromPostgisGeometry.GetOrAdd(type, t2 => typeof(PostgisGeometry).IsAssignableFrom(type.IsArray ? type.GetElementType() : type))) + { + var pam = AppendParamter(specialParams, null, type, value); + return pam.ParameterName; + } + value = getParamterValue(type, value); + var type2 = value.GetType(); + if (type2 == typeof(byte[])) + { + var bytes = value as byte[]; + var sb = new StringBuilder().Append("'\\x"); + foreach (var vc in bytes) + { + if (vc < 10) sb.Append("0"); + sb.Append(vc.ToString("X")); + } + return sb.Append("'").ToString(); //val = Encoding.UTF8.GetString(val as byte[]); + } + else if (type2 == typeof(TimeSpan) || type2 == typeof(TimeSpan?)) + { + var ts = (TimeSpan)value; + return $"'{Math.Min(24, (int)Math.Floor(ts.TotalHours))}:{ts.Minutes}:{ts.Seconds}'"; + } + else if (value is Array) + { + var valueArr = value as Array; + var eleType = type2.GetElementType(); + var len = valueArr.GetLength(0); + var sb = new StringBuilder().Append("ARRAY["); + for (var a = 0; a < len; a++) + { + var item = valueArr.GetValue(a); + if (a > 0) sb.Append(","); + sb.Append(GetNoneParamaterSqlValue(specialParams, eleType, item)); + } + sb.Append("]"); + var dbinfo = _orm.CodeFirst.GetDbInfo(type); + if (dbinfo.HasValue) sb.Append("::").Append(dbinfo.Value.dbtype); + return sb.ToString(); + } + else if (type2 == typeof(BitArray)) + { + return $"'{(value as BitArray).To1010()}'"; + } + else if (type2 == typeof(NpgsqlLine) || type2 == typeof(NpgsqlLine?)) + { + var line = value.ToString(); + return line == "{0,0,0}" ? "'{0,-1,-1}'" : $"'{line}'"; + } + else if (type2 == typeof((IPAddress Address, int Subnet)) || type2 == typeof((IPAddress Address, int Subnet)?)) + { + var cidr = ((IPAddress Address, int Subnet))value; + return $"'{cidr.Address}/{cidr.Subnet}'"; + } + else if (dicGetParamterValue.ContainsKey(type2.FullName)) + { + value = string.Concat(value); + } + return FormatSql("{0}", value, 1); + } + } } diff --git a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerDelete.cs b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerDelete.cs index f604a4f2..b227068f 100644 --- a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerDelete.cs +++ b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerDelete.cs @@ -5,84 +5,101 @@ using System.Data; using System.Text; using System.Threading.Tasks; -namespace FreeSql.SqlServer.Curd { +namespace FreeSql.SqlServer.Curd +{ - class SqlServerDelete : Internal.CommonProvider.DeleteProvider where T1 : class { - public SqlServerDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + class SqlServerDelete : Internal.CommonProvider.DeleteProvider where T1 : class + { + public SqlServerDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override List ExecuteDeleted() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + public override List ExecuteDeleted() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(" OUTPUT "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append("DELETED.").Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } + var sb = new StringBuilder(); + sb.Append(" OUTPUT "); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append("DELETED.").Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } - var validx = sql.IndexOf(" WHERE "); - if (validx == -1) throw new ArgumentException("找不到 WHERE "); - sb.Insert(0, sql.Substring(0, validx)); - sb.Append(sql.Substring(validx)); + var validx = sql.IndexOf(" WHERE "); + if (validx == -1) throw new ArgumentException("找不到 WHERE "); + sb.Insert(0, sql.Substring(0, validx)); + sb.Append(sql.Substring(validx)); - sql = sb.ToString(); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async public override Task> ExecuteDeletedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + sql = sb.ToString(); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async public override Task> ExecuteDeletedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(" OUTPUT "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append("DELETED.").Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } + var sb = new StringBuilder(); + sb.Append(" OUTPUT "); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append("DELETED.").Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, _commonUtils.QuoteSqlName(col.Attribute.Name))).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } - var validx = sql.IndexOf(" WHERE "); - if (validx == -1) throw new ArgumentException("找不到 WHERE "); - sb.Insert(0, sql.Substring(0, validx)); - sb.Append(sql.Substring(validx)); + var validx = sql.IndexOf(" WHERE "); + if (validx == -1) throw new ArgumentException("找不到 WHERE "); + sb.Insert(0, sql.Substring(0, validx)); + sb.Append(sql.Substring(validx)); - sql = sb.ToString(); - var dbParms = _params.ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - } + sql = sb.ToString(); + var dbParms = _params.ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Delete, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + } } diff --git a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsert.cs b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsert.cs index a0c71ca1..4fe5ba0b 100644 --- a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsert.cs +++ b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerInsert.cs @@ -7,133 +7,162 @@ using System.Data.Common; using System.Text; using System.Threading.Tasks; -namespace FreeSql.SqlServer.Curd { +namespace FreeSql.SqlServer.Curd +{ - class SqlServerInsert : Internal.CommonProvider.InsertProvider where T1 : class { - public SqlServerInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) - : base(orm, commonUtils, commonExpression) { - } + class SqlServerInsert : Internal.CommonProvider.InsertProvider where T1 : class + { + public SqlServerInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + : base(orm, commonUtils, commonExpression) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(1000, 2100); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(1000, 2100); - public override long ExecuteIdentity() => base.SplitExecuteIdentity(1000, 2100); - public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(1000, 2100); - public override List ExecuteInserted() => base.SplitExecuteInserted(1000, 2100); - public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(1000, 2100); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(1000, 2100); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(1000, 2100); + public override long ExecuteIdentity() => base.SplitExecuteIdentity(1000, 2100); + public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(1000, 2100); + public override List ExecuteInserted() => base.SplitExecuteInserted(1000, 2100); + public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(1000, 2100); - protected override long RawExecuteIdentity() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + protected override long RawExecuteIdentity() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - sql = string.Concat(sql, "; SELECT SCOPE_IDENTITY();"); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - long ret = 0; - Exception exception = null; - try { - long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out ret); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task RawExecuteIdentityAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + sql = string.Concat(sql, "; SELECT SCOPE_IDENTITY();"); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + long ret = 0; + Exception exception = null; + try + { + long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out ret); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task RawExecuteIdentityAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - sql = string.Concat(sql, "; SELECT SCOPE_IDENTITY();"); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - long ret = 0; - Exception exception = null; - try { - long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out ret); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } + sql = string.Concat(sql, "; SELECT SCOPE_IDENTITY();"); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + long ret = 0; + Exception exception = null; + try + { + long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out ret); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } - protected override List RawExecuteInserted() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + protected override List RawExecuteInserted() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(" OUTPUT "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } + var sb = new StringBuilder(); + sb.Append(" OUTPUT "); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } - var validx = sql.IndexOf(") VALUES"); - if (validx == -1) throw new ArgumentException("找不到 VALUES"); - sb.Insert(0, sql.Substring(0, validx + 1)); - sb.Append(sql.Substring(validx + 1)); + var validx = sql.IndexOf(") VALUES"); + if (validx == -1) throw new ArgumentException("找不到 VALUES"); + sb.Insert(0, sql.Substring(0, validx + 1)); + sb.Append(sql.Substring(validx + 1)); - sql = sb.ToString(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task> RawExecuteInsertedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + sql = sb.ToString(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task> RawExecuteInsertedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(" OUTPUT "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } + var sb = new StringBuilder(); + sb.Append(" OUTPUT "); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } - var validx = sql.IndexOf(") VALUES"); - if (validx == -1) throw new ArgumentException("找不到 VALUES"); - sb.Insert(0, sql.Substring(0, validx + 1)); - sb.Append(sql.Substring(validx + 1)); + var validx = sql.IndexOf(") VALUES"); + if (validx == -1) throw new ArgumentException("找不到 VALUES"); + sb.Insert(0, sql.Substring(0, validx + 1)); + sb.Append(sql.Substring(validx + 1)); - sql = sb.ToString(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, _params); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - } + sql = sb.ToString(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, _params); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerSelect.cs b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerSelect.cs index 1586f0af..afc7347f 100644 --- a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerSelect.cs +++ b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerSelect.cs @@ -6,220 +6,259 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.SqlServer.Curd { +namespace FreeSql.SqlServer.Curd +{ - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class { + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class + { - internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) - => (_commonUtils as SqlServerUtils).IsSelectRowNumber ? - ToSqlStaticRowNumber(_commonUtils, _select, _distinct, field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, tableRuleInvoke, _orm) : - ToSqlStaticOffsetFetchNext(_commonUtils, _select, _distinct, field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, tableRuleInvoke, _orm); + internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) + => (_commonUtils as SqlServerUtils).IsSelectRowNumber ? + ToSqlStaticRowNumber(_commonUtils, _select, _distinct, field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, tableRuleInvoke, _orm) : + ToSqlStaticOffsetFetchNext(_commonUtils, _select, _distinct, field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, tableRuleInvoke, _orm); - #region SqlServer 2005 row_number - internal static string ToSqlStaticRowNumber(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) { - if (_orm.CodeFirst.IsAutoSyncStructure) - _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); + #region SqlServer 2005 row_number + internal static string ToSqlStaticRowNumber(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) + { + if (_orm.CodeFirst.IsAutoSyncStructure) + _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); - var sb = new StringBuilder(); - var sbnav = new StringBuilder(); - sb.Append(_select); - if (_distinct) sb.Append("DISTINCT "); - if (_limit > 0) sb.Append("TOP ").Append(_skip + _limit).Append(" "); - sb.Append(field); - if (_skip > 0) { - if (string.IsNullOrEmpty(_orderby)) { - var pktb = _tables.Where(a => a.Table.Primarys.Any()).FirstOrDefault(); - if (pktb != null) _orderby = string.Concat(" \r\nORDER BY ", pktb.Alias, ".", _commonUtils.QuoteSqlName(pktb?.Table.Primarys.First().Attribute.Name)); - else _orderby = string.Concat(" \r\nORDER BY ", _tables.First().Alias, ".", _commonUtils.QuoteSqlName(_tables.First().Table.Columns.First().Value.Attribute.Name)); - } - sb.Append(", ROW_NUMBER() OVER(").Append(_orderby).Append(") AS __rownum__"); - } - sb.Append(" \r\nFROM "); - var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); - var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); - for (var a = 0; a < tbsfrom.Length; a++) { - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); - if (tbsjoin.Length > 0) { - //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 - for (var b = 1; b < tbsfrom.Length; b++) { - sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); - if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); - else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); - } - break; - } else { - if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); - if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); - } - if (a < tbsfrom.Length - 1) sb.Append(", "); - } - foreach (var tb in tbsjoin) { - if (tb.Type == SelectTableInfoType.Parent) continue; - switch (tb.Type) { - case SelectTableInfoType.LeftJoin: - sb.Append(" \r\nLEFT JOIN "); - break; - case SelectTableInfoType.InnerJoin: - sb.Append(" \r\nINNER JOIN "); - break; - case SelectTableInfoType.RightJoin: - sb.Append(" \r\nRIGHT JOIN "); - break; - } - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); - if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); - } - if (_join.Length > 0) sb.Append(_join); + var sb = new StringBuilder(); + var sbnav = new StringBuilder(); + sb.Append(_select); + if (_distinct) sb.Append("DISTINCT "); + if (_limit > 0) sb.Append("TOP ").Append(_skip + _limit).Append(" "); + sb.Append(field); + if (_skip > 0) + { + if (string.IsNullOrEmpty(_orderby)) + { + var pktb = _tables.Where(a => a.Table.Primarys.Any()).FirstOrDefault(); + if (pktb != null) _orderby = string.Concat(" \r\nORDER BY ", pktb.Alias, ".", _commonUtils.QuoteSqlName(pktb?.Table.Primarys.First().Attribute.Name)); + else _orderby = string.Concat(" \r\nORDER BY ", _tables.First().Alias, ".", _commonUtils.QuoteSqlName(_tables.First().Table.Columns.First().Value.Attribute.Name)); + } + sb.Append(", ROW_NUMBER() OVER(").Append(_orderby).Append(") AS __rownum__"); + } + sb.Append(" \r\nFROM "); + var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); + var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); + for (var a = 0; a < tbsfrom.Length; a++) + { + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); + if (tbsjoin.Length > 0) + { + //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 + for (var b = 1; b < tbsfrom.Length; b++) + { + sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); + if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); + else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); + } + break; + } + else + { + if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); + if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); + } + if (a < tbsfrom.Length - 1) sb.Append(", "); + } + foreach (var tb in tbsjoin) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + switch (tb.Type) + { + case SelectTableInfoType.LeftJoin: + sb.Append(" \r\nLEFT JOIN "); + break; + case SelectTableInfoType.InnerJoin: + sb.Append(" \r\nINNER JOIN "); + break; + case SelectTableInfoType.RightJoin: + sb.Append(" \r\nRIGHT JOIN "); + break; + } + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); + if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); + } + if (_join.Length > 0) sb.Append(_join); - sbnav.Append(_where); - foreach (var tb in _tables) { - if (tb.Type == SelectTableInfoType.Parent) continue; - if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) - sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); - } - if (sbnav.Length > 0) { - sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); - } - if (string.IsNullOrEmpty(_groupby) == false) { - sb.Append(_groupby); - if (string.IsNullOrEmpty(_having) == false) - sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); - } - if (_skip <= 0) - sb.Append(_orderby); - else - sb.Insert(0, "WITH t AS ( ").Append(" ) SELECT t.* FROM t where __rownum__ > ").Append(_skip); + sbnav.Append(_where); + foreach (var tb in _tables) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) + sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); + } + if (sbnav.Length > 0) + { + sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); + } + if (string.IsNullOrEmpty(_groupby) == false) + { + sb.Append(_groupby); + if (string.IsNullOrEmpty(_having) == false) + sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); + } + if (_skip <= 0) + sb.Append(_orderby); + else + sb.Insert(0, "WITH t AS ( ").Append(" ) SELECT t.* FROM t where __rownum__ > ").Append(_skip); - sbnav.Clear(); - return sb.ToString(); - } - #endregion + sbnav.Clear(); + return sb.ToString(); + } + #endregion - #region SqlServer 2012+ offset feach next - internal static string ToSqlStaticOffsetFetchNext(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) { - if (_orm.CodeFirst.IsAutoSyncStructure) - _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); + #region SqlServer 2012+ offset feach next + internal static string ToSqlStaticOffsetFetchNext(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) + { + if (_orm.CodeFirst.IsAutoSyncStructure) + _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); - var sb = new StringBuilder(); - var sbnav = new StringBuilder(); - sb.Append(_select); - if (_distinct) sb.Append("DISTINCT "); - if (_skip <= 0 && _limit > 0) sb.Append("TOP ").Append(_limit).Append(" "); - sb.Append(field); - sb.Append(" \r\nFROM "); - var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); - var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); - for (var a = 0; a < tbsfrom.Length; a++) { - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); - if (tbsjoin.Length > 0) { - //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 - for (var b = 1; b < tbsfrom.Length; b++) { - sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); - if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); - else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); - } - break; - } else { - if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); - if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); - } - if (a < tbsfrom.Length - 1) sb.Append(", "); - } - foreach (var tb in tbsjoin) { - if (tb.Type == SelectTableInfoType.Parent) continue; - switch (tb.Type) { - case SelectTableInfoType.LeftJoin: - sb.Append(" \r\nLEFT JOIN "); - break; - case SelectTableInfoType.InnerJoin: - sb.Append(" \r\nINNER JOIN "); - break; - case SelectTableInfoType.RightJoin: - sb.Append(" \r\nRIGHT JOIN "); - break; - } - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); - if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); - } - if (_join.Length > 0) sb.Append(_join); + var sb = new StringBuilder(); + var sbnav = new StringBuilder(); + sb.Append(_select); + if (_distinct) sb.Append("DISTINCT "); + if (_skip <= 0 && _limit > 0) sb.Append("TOP ").Append(_limit).Append(" "); + sb.Append(field); + sb.Append(" \r\nFROM "); + var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); + var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); + for (var a = 0; a < tbsfrom.Length; a++) + { + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); + if (tbsjoin.Length > 0) + { + //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 + for (var b = 1; b < tbsfrom.Length; b++) + { + sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); + if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); + else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); + } + break; + } + else + { + if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); + if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); + } + if (a < tbsfrom.Length - 1) sb.Append(", "); + } + foreach (var tb in tbsjoin) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + switch (tb.Type) + { + case SelectTableInfoType.LeftJoin: + sb.Append(" \r\nLEFT JOIN "); + break; + case SelectTableInfoType.InnerJoin: + sb.Append(" \r\nINNER JOIN "); + break; + case SelectTableInfoType.RightJoin: + sb.Append(" \r\nRIGHT JOIN "); + break; + } + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); + if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); + } + if (_join.Length > 0) sb.Append(_join); - sbnav.Append(_where); - foreach (var tb in _tables) { - if (tb.Type == SelectTableInfoType.Parent) continue; - if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) - sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); - } - if (sbnav.Length > 0) { - sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); - } - if (string.IsNullOrEmpty(_groupby) == false) { - sb.Append(_groupby); - if (string.IsNullOrEmpty(_having) == false) - sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); - } - if (_skip > 0) { - if (string.IsNullOrEmpty(_orderby)) { - var pktb = _tables.Where(a => a.Table.Primarys.Any()).FirstOrDefault(); - if (pktb != null) _orderby = string.Concat(" \r\nORDER BY ", pktb.Alias, ".", _commonUtils.QuoteSqlName(pktb?.Table.Primarys.First().Attribute.Name)); - else _orderby = string.Concat(" \r\nORDER BY ", _tables.First().Alias, ".", _commonUtils.QuoteSqlName(_tables.First().Table.Columns.First().Value.Attribute.Name)); - } - sb.Append(_orderby).Append($" \r\nOFFSET {_skip} ROW"); - if (_limit > 0) sb.Append($" \r\nFETCH NEXT {_limit} ROW ONLY"); - } else { - sb.Append(_orderby); - } + sbnav.Append(_where); + foreach (var tb in _tables) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) + sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); + } + if (sbnav.Length > 0) + { + sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); + } + if (string.IsNullOrEmpty(_groupby) == false) + { + sb.Append(_groupby); + if (string.IsNullOrEmpty(_having) == false) + sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); + } + if (_skip > 0) + { + if (string.IsNullOrEmpty(_orderby)) + { + var pktb = _tables.Where(a => a.Table.Primarys.Any()).FirstOrDefault(); + if (pktb != null) _orderby = string.Concat(" \r\nORDER BY ", pktb.Alias, ".", _commonUtils.QuoteSqlName(pktb?.Table.Primarys.First().Attribute.Name)); + else _orderby = string.Concat(" \r\nORDER BY ", _tables.First().Alias, ".", _commonUtils.QuoteSqlName(_tables.First().Table.Columns.First().Value.Attribute.Name)); + } + sb.Append(_orderby).Append($" \r\nOFFSET {_skip} ROW"); + if (_limit > 0) sb.Append($" \r\nFETCH NEXT {_limit} ROW ONLY"); + } + else + { + sb.Append(_orderby); + } - sbnav.Clear(); - return sb.ToString(); - } - #endregion + sbnav.Clear(); + return sb.ToString(); + } + #endregion - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqlServerSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class { - public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqlServerSelect(_orm, _commonUtils, _commonExpression, null); SqlServerSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqlServerSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class + { + public SqlServerSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqlServerSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } } diff --git a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerUpdate.cs b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerUpdate.cs index 871ea913..a079557a 100644 --- a/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerUpdate.cs +++ b/Providers/FreeSql.Provider.SqlServer/Curd/SqlServerUpdate.cs @@ -7,121 +7,144 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.SqlServer.Curd { +namespace FreeSql.SqlServer.Curd +{ - class SqlServerUpdate : Internal.CommonProvider.UpdateProvider where T1 : class { + class SqlServerUpdate : Internal.CommonProvider.UpdateProvider where T1 : class + { - public SqlServerUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + public SqlServerUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 2100); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 2100); - public override List ExecuteUpdated() => base.SplitExecuteUpdated(500, 2100); - public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(500, 2100); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(500, 2100); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(500, 2100); + public override List ExecuteUpdated() => base.SplitExecuteUpdated(500, 2100); + public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(500, 2100); - protected override List RawExecuteUpdated() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + protected override List RawExecuteUpdated() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(" OUTPUT "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } + var sb = new StringBuilder(); + sb.Append(" OUTPUT "); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } - var validx = sql.IndexOf(" WHERE "); - if (validx == -1) throw new ArgumentException("找不到 WHERE "); - sb.Insert(0, sql.Substring(0, validx)); - sb.Append(sql.Substring(validx)); + var validx = sql.IndexOf(" WHERE "); + if (validx == -1) throw new ArgumentException("找不到 WHERE "); + sb.Insert(0, sql.Substring(0, validx)); + sb.Append(sql.Substring(validx)); - sql = sb.ToString(); - var dbParms = _params.Concat(_paramsSource).ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); - ValidateVersionAndThrow(ret.Count); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task> RawExecuteUpdatedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + sql = sb.ToString(); + var dbParms = _params.Concat(_paramsSource).ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = _orm.Ado.Query(_connection, _transaction, CommandType.Text, sql, dbParms); + ValidateVersionAndThrow(ret.Count); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task> RawExecuteUpdatedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - var sb = new StringBuilder(); - sb.Append(" OUTPUT "); - var colidx = 0; - foreach (var col in _table.Columns.Values) { - if (colidx > 0) sb.Append(", "); - sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); - ++colidx; - } + var sb = new StringBuilder(); + sb.Append(" OUTPUT "); + var colidx = 0; + foreach (var col in _table.Columns.Values) + { + if (colidx > 0) sb.Append(", "); + sb.Append(_commonUtils.QuoteReadColumn(col.Attribute.MapType, $"INSERTED.{_commonUtils.QuoteSqlName(col.Attribute.Name)}")).Append(" as ").Append(_commonUtils.QuoteSqlName(col.CsName)); + ++colidx; + } - var validx = sql.IndexOf(" WHERE "); - if (validx == -1) throw new ArgumentException("找不到 WHERE "); - sb.Insert(0, sql.Substring(0, validx)); - sb.Append(sql.Substring(validx)); + var validx = sql.IndexOf(" WHERE "); + if (validx == -1) throw new ArgumentException("找不到 WHERE "); + sb.Insert(0, sql.Substring(0, validx)); + sb.Append(sql.Substring(validx)); - sql = sb.ToString(); - var dbParms = _params.Concat(_paramsSource).ToArray(); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); - _orm.Aop.CurdBefore?.Invoke(this, before); - var ret = new List(); - Exception exception = null; - try { - ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); - ValidateVersionAndThrow(ret.Count); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } + sql = sb.ToString(); + var dbParms = _params.Concat(_paramsSource).ToArray(); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Update, sql, dbParms); + _orm.Aop.CurdBefore?.Invoke(this, before); + var ret = new List(); + Exception exception = null; + try + { + ret = await _orm.Ado.QueryAsync(_connection, _transaction, CommandType.Text, sql, dbParms); + ValidateVersionAndThrow(ret.Count); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } - protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) { - if (_table.Primarys.Length == 1) { - caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); - return; - } - caseWhen.Append("("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) caseWhen.Append(", "); - caseWhen.Append("cast(").Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))).Append(" as varchar)"); - ++pkidx; - } - caseWhen.Append(")"); - } + protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) + { + if (_table.Primarys.Length == 1) + { + caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); + return; + } + caseWhen.Append("("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) caseWhen.Append(", "); + caseWhen.Append("cast(").Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))).Append(" as varchar)"); + ++pkidx; + } + caseWhen.Append(")"); + } - protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) { - if (_table.Primarys.Length == 1) { - sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); - return; - } - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) sb.Append(", "); - sb.Append("cast(").Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))).Append(" as varchar)"); - ++pkidx; - } - } - } + protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) + { + if (_table.Primarys.Length == 1) + { + sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); + return; + } + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) sb.Append(", "); + sb.Append("cast(").Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))).Append(" as varchar)"); + ++pkidx; + } + } + } } diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerAdo/SqlServerAdo.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerAdo/SqlServerAdo.cs index 9168c070..1849c39e 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerAdo/SqlServerAdo.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerAdo/SqlServerAdo.cs @@ -7,59 +7,72 @@ using System.Data.SqlClient; using System.Text; using System.Threading; -namespace FreeSql.SqlServer { - class SqlServerAdo : FreeSql.Internal.CommonProvider.AdoProvider { - public SqlServerAdo() : base(DataType.SqlServer) { } - public SqlServerAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.SqlServer) { - base._util = util; - if (!string.IsNullOrEmpty(masterConnectionString)) - MasterPool = new SqlServerConnectionPool("主库", masterConnectionString, null, null); - if (slaveConnectionStrings != null) { - foreach (var slaveConnectionString in slaveConnectionStrings) { - var slavePool = new SqlServerConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); - SlavePools.Add(slavePool); - } - } - } - static DateTime dt1970 = new DateTime(1970, 1, 1); - public override object AddslashesProcessParam(object param, Type mapType) { - if (param == null) return "NULL"; - if (mapType != null && mapType != param.GetType()) - param = Utils.GetDataReaderValue(mapType, param); - if (param is bool || param is bool?) - return (bool)param ? 1 : 0; - else if (param is string || param is char) - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - else if (param is Enum) - return ((Enum)param).ToInt64(); - else if (decimal.TryParse(string.Concat(param), out var trydec)) - return param; - else if (param is DateTime || param is DateTime?) { - if (param.Equals(DateTime.MinValue) == true) param = new DateTime(1970, 1, 1); - return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.fff"), "'"); - } else if (param is DateTimeOffset || param is DateTimeOffset?) { - if (param.Equals(DateTimeOffset.MinValue) == true) param = new DateTimeOffset(new DateTime(1970, 1, 1), TimeSpan.Zero); - return string.Concat("'", ((DateTimeOffset)param).ToString("yyyy-MM-dd HH:mm:ss.fff zzzz"), "'"); - } else if (param is TimeSpan || param is TimeSpan?) - return ((TimeSpan)param).TotalSeconds; - else if (param is IEnumerable) { - var sb = new StringBuilder(); - var ie = param as IEnumerable; - foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); - return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); - } - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - //if (param is string) return string.Concat('N', nparms[a]); - } +namespace FreeSql.SqlServer +{ + class SqlServerAdo : FreeSql.Internal.CommonProvider.AdoProvider + { + public SqlServerAdo() : base(DataType.SqlServer) { } + public SqlServerAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.SqlServer) + { + base._util = util; + if (!string.IsNullOrEmpty(masterConnectionString)) + MasterPool = new SqlServerConnectionPool("主库", masterConnectionString, null, null); + if (slaveConnectionStrings != null) + { + foreach (var slaveConnectionString in slaveConnectionStrings) + { + var slavePool = new SqlServerConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); + SlavePools.Add(slavePool); + } + } + } + static DateTime dt1970 = new DateTime(1970, 1, 1); + public override object AddslashesProcessParam(object param, Type mapType) + { + if (param == null) return "NULL"; + if (mapType != null && mapType != param.GetType()) + param = Utils.GetDataReaderValue(mapType, param); + if (param is bool || param is bool?) + return (bool)param ? 1 : 0; + else if (param is string || param is char) + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + else if (param is Enum) + return ((Enum)param).ToInt64(); + else if (decimal.TryParse(string.Concat(param), out var trydec)) + return param; + else if (param is DateTime || param is DateTime?) + { + if (param.Equals(DateTime.MinValue) == true) param = new DateTime(1970, 1, 1); + return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss.fff"), "'"); + } + else if (param is DateTimeOffset || param is DateTimeOffset?) + { + if (param.Equals(DateTimeOffset.MinValue) == true) param = new DateTimeOffset(new DateTime(1970, 1, 1), TimeSpan.Zero); + return string.Concat("'", ((DateTimeOffset)param).ToString("yyyy-MM-dd HH:mm:ss.fff zzzz"), "'"); + } + else if (param is TimeSpan || param is TimeSpan?) + return ((TimeSpan)param).TotalSeconds; + else if (param is IEnumerable) + { + var sb = new StringBuilder(); + var ie = param as IEnumerable; + foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); + return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); + } + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + //if (param is string) return string.Concat('N', nparms[a]); + } - protected override DbCommand CreateCommand() { - return new SqlCommand(); - } + protected override DbCommand CreateCommand() + { + return new SqlCommand(); + } - protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) { - (pool as SqlServerConnectionPool).Return(conn, ex); - } + protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) + { + (pool as SqlServerConnectionPool).Return(conn, ex); + } - protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); - } + protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerAdo/SqlServerConnectionPool.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerAdo/SqlServerConnectionPool.cs index f3f6b6d1..605f0eb9 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerAdo/SqlServerConnectionPool.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerAdo/SqlServerConnectionPool.cs @@ -8,174 +8,215 @@ using System.Data.SqlClient; using System.Text.RegularExpressions; using System.Threading.Tasks; -namespace FreeSql.SqlServer { +namespace FreeSql.SqlServer +{ - class SqlServerConnectionPool : ObjectPool { + class SqlServerConnectionPool : ObjectPool + { - internal Action availableHandler; - internal Action unavailableHandler; + internal Action availableHandler; + internal Action unavailableHandler; - public SqlServerConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) { - var policy = new SqlServerConnectionPoolPolicy { - _pool = this, - Name = name - }; - this.Policy = policy; - policy.ConnectionString = connectionString; + public SqlServerConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) + { + var policy = new SqlServerConnectionPoolPolicy + { + _pool = this, + Name = name + }; + this.Policy = policy; + policy.ConnectionString = connectionString; - this.availableHandler = availableHandler; - this.unavailableHandler = unavailableHandler; - } + this.availableHandler = availableHandler; + this.unavailableHandler = unavailableHandler; + } - public void Return(Object obj, Exception exception, bool isRecreate = false) { - if (exception != null && exception is SqlException) { + public void Return(Object obj, Exception exception, bool isRecreate = false) + { + if (exception != null && exception is SqlException) + { - if (obj.Value.Ping() == false) { + if (obj.Value.Ping() == false) + { - base.SetUnavailable(exception); - } - } - base.Return(obj, isRecreate); - } - } + base.SetUnavailable(exception); + } + } + base.Return(obj, isRecreate); + } + } - class SqlServerConnectionPoolPolicy : IPolicy { + class SqlServerConnectionPoolPolicy : IPolicy + { - internal SqlServerConnectionPool _pool; - public string Name { get; set; } = "SqlServer SqlConnection 对象池"; - public int PoolSize { get; set; } = 100; - public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); - public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; - public int AsyncGetCapacity { get; set; } = 10000; - public bool IsThrowGetTimeoutException { get; set; } = true; - public int CheckAvailableInterval { get; set; } = 5; + internal SqlServerConnectionPool _pool; + public string Name { get; set; } = "SqlServer SqlConnection 对象池"; + public int PoolSize { get; set; } = 100; + public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); + public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; + public int AsyncGetCapacity { get; set; } = 10000; + public bool IsThrowGetTimeoutException { get; set; } = true; + public int CheckAvailableInterval { get; set; } = 5; - static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - private string _connectionString; - public string ConnectionString { - get => _connectionString; - set { - _connectionString = value ?? ""; + static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + private string _connectionString; + public string ConnectionString + { + get => _connectionString; + set + { + _connectionString = value ?? ""; - var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)"; - Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100; - var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); - PoolSize = poolsize + connStrIncr; - _connectionString = m.Success ? - Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) : - $"{_connectionString};Max pool size={PoolSize}"; + var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)"; + Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100; + var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); + PoolSize = poolsize + connStrIncr; + _connectionString = m.Success ? + Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) : + $"{_connectionString};Max pool size={PoolSize}"; - pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - var minPoolSize = 0; - pattern = @"Min\s*pool\s*size\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - minPoolSize = int.Parse(m.Groups[1].Value); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + var minPoolSize = 0; + pattern = @"Min\s*pool\s*size\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + minPoolSize = int.Parse(m.Groups[1].Value); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); - } - } + FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); + } + } - public bool OnCheckAvailable(Object obj) { - if (obj.Value.State == ConnectionState.Closed) obj.Value.Open(); - return obj.Value.Ping(true); - } + public bool OnCheckAvailable(Object obj) + { + if (obj.Value.State == ConnectionState.Closed) obj.Value.Open(); + return obj.Value.Ping(true); + } - public DbConnection OnCreate() { - var conn = new SqlConnection(_connectionString); - return conn; - } + public DbConnection OnCreate() + { + var conn = new SqlConnection(_connectionString); + return conn; + } - public void OnDestroy(DbConnection obj) { - if (obj.State != ConnectionState.Closed) obj.Close(); - obj.Dispose(); - } + public void OnDestroy(DbConnection obj) + { + if (obj.State != ConnectionState.Closed) obj.Close(); + obj.Dispose(); + } - public void OnGet(Object obj) { + public void OnGet(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) + { - try { - obj.Value.Open(); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + obj.Value.Open(); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - async public Task OnGetAsync(Object obj) { + async public Task OnGetAsync(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) + { - try { - await obj.Value.OpenAsync(); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + await obj.Value.OpenAsync(); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - public void OnGetTimeout() { + public void OnGetTimeout() + { - } + } - public void OnReturn(Object obj) { - if (obj.Value.State != ConnectionState.Closed) try { obj.Value.Close(); } catch { } - } + public void OnReturn(Object obj) + { + if (obj.Value.State != ConnectionState.Closed) try { obj.Value.Close(); } catch { } + } - public void OnAvailable() { - _pool.availableHandler?.Invoke(); - } + public void OnAvailable() + { + _pool.availableHandler?.Invoke(); + } - public void OnUnavailable() { - _pool.unavailableHandler?.Invoke(); - } - } + public void OnUnavailable() + { + _pool.unavailableHandler?.Invoke(); + } + } - static class DbConnectionExtensions { + static class DbConnectionExtensions + { - static DbCommand PingCommand(DbConnection conn) { - var cmd = conn.CreateCommand(); - cmd.CommandTimeout = 5; - cmd.CommandText = "select 1"; - return cmd; - } - public static bool Ping(this DbConnection that, bool isThrow = false) { - try { - PingCommand(that).ExecuteNonQuery(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - async public static Task PingAsync(this DbConnection that, bool isThrow = false) { - try { - await PingCommand(that).ExecuteNonQueryAsync(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - } + static DbCommand PingCommand(DbConnection conn) + { + var cmd = conn.CreateCommand(); + cmd.CommandTimeout = 5; + cmd.CommandText = "select 1"; + return cmd; + } + public static bool Ping(this DbConnection that, bool isThrow = false) + { + try + { + PingCommand(that).ExecuteNonQuery(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + async public static Task PingAsync(this DbConnection that, bool isThrow = false) + { + try + { + await PingCommand(that).ExecuteNonQueryAsync(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + } } diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs index 6df8fd72..ea78f7f4 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerCodeFirst.cs @@ -10,63 +10,71 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; -namespace FreeSql.SqlServer { +namespace FreeSql.SqlServer +{ - class SqlServerCodeFirst : Internal.CommonProvider.CodeFirstProvider { - - public SqlServerCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } + class SqlServerCodeFirst : Internal.CommonProvider.CodeFirstProvider + { - static object _dicCsToDbLock = new object(); - static Dictionary _dicCsToDb = new Dictionary() { - { typeof(bool).FullName, (SqlDbType.Bit, "bit","bit NOT NULL", null, false, false) },{ typeof(bool?).FullName, (SqlDbType.Bit, "bit","bit", null, true, null) }, + public SqlServerCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } - { typeof(sbyte).FullName, (SqlDbType.SmallInt, "smallint", "smallint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) }, - { typeof(short).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) }, - { typeof(int).FullName, (SqlDbType.Int, "int", "int NOT NULL", false, false, 0) },{ typeof(int?).FullName, (SqlDbType.Int, "int", "int", false, true, null) }, - { typeof(long).FullName, (SqlDbType.BigInt, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(long?).FullName, (SqlDbType.BigInt, "bigint","bigint", false, true, null) }, + static object _dicCsToDbLock = new object(); + static Dictionary _dicCsToDb = new Dictionary() { + { typeof(bool).FullName, (SqlDbType.Bit, "bit","bit NOT NULL", null, false, false) },{ typeof(bool?).FullName, (SqlDbType.Bit, "bit","bit", null, true, null) }, - { typeof(byte).FullName, (SqlDbType.TinyInt, "tinyint","tinyint NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (SqlDbType.TinyInt, "tinyint","tinyint", true, true, null) }, - { typeof(ushort).FullName, (SqlDbType.Int, "int","int NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (SqlDbType.Int, "int", "int", true, true, null) }, - { typeof(uint).FullName, (SqlDbType.BigInt, "bigint", "bigint NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (SqlDbType.BigInt, "bigint", "bigint", true, true, null) }, - { typeof(ulong).FullName, (SqlDbType.Decimal, "decimal", "decimal(20,0) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (SqlDbType.Decimal, "decimal", "decimal(20,0)", true, true, null) }, + { typeof(sbyte).FullName, (SqlDbType.SmallInt, "smallint", "smallint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) }, + { typeof(short).FullName, (SqlDbType.SmallInt, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, (SqlDbType.SmallInt, "smallint", "smallint", false, true, null) }, + { typeof(int).FullName, (SqlDbType.Int, "int", "int NOT NULL", false, false, 0) },{ typeof(int?).FullName, (SqlDbType.Int, "int", "int", false, true, null) }, + { typeof(long).FullName, (SqlDbType.BigInt, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(long?).FullName, (SqlDbType.BigInt, "bigint","bigint", false, true, null) }, - { typeof(double).FullName, (SqlDbType.Float, "float", "float NOT NULL", false, false, 0) },{ typeof(double?).FullName, (SqlDbType.Float, "float", "float", false, true, null) }, - { typeof(float).FullName, (SqlDbType.Real, "real","real NOT NULL", false, false, 0) },{ typeof(float?).FullName, (SqlDbType.Real, "real","real", false, true, null) }, - { typeof(decimal).FullName, (SqlDbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (SqlDbType.Decimal, "decimal", "decimal(10,2)", false, true, null) }, + { typeof(byte).FullName, (SqlDbType.TinyInt, "tinyint","tinyint NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (SqlDbType.TinyInt, "tinyint","tinyint", true, true, null) }, + { typeof(ushort).FullName, (SqlDbType.Int, "int","int NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (SqlDbType.Int, "int", "int", true, true, null) }, + { typeof(uint).FullName, (SqlDbType.BigInt, "bigint", "bigint NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (SqlDbType.BigInt, "bigint", "bigint", true, true, null) }, + { typeof(ulong).FullName, (SqlDbType.Decimal, "decimal", "decimal(20,0) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (SqlDbType.Decimal, "decimal", "decimal(20,0)", true, true, null) }, - { typeof(TimeSpan).FullName, (SqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (SqlDbType.Time, "time", "time",false, true, null) }, - { typeof(DateTime).FullName, (SqlDbType.DateTime, "datetime", "datetime NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (SqlDbType.DateTime, "datetime", "datetime", false, true, null) }, - { typeof(DateTimeOffset).FullName, (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset NOT NULL", false, false, new DateTimeOffset(new DateTime(1970,1,1), TimeSpan.Zero)) },{ typeof(DateTimeOffset?).FullName, (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset", false, true, null) }, + { typeof(double).FullName, (SqlDbType.Float, "float", "float NOT NULL", false, false, 0) },{ typeof(double?).FullName, (SqlDbType.Float, "float", "float", false, true, null) }, + { typeof(float).FullName, (SqlDbType.Real, "real","real NOT NULL", false, false, 0) },{ typeof(float?).FullName, (SqlDbType.Real, "real","real", false, true, null) }, + { typeof(decimal).FullName, (SqlDbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (SqlDbType.Decimal, "decimal", "decimal(10,2)", false, true, null) }, - { typeof(byte[]).FullName, (SqlDbType.VarBinary, "varbinary", "varbinary(255)", false, null, new byte[0]) }, - { typeof(string).FullName, (SqlDbType.NVarChar, "nvarchar", "nvarchar(255)", false, null, "") }, + { typeof(TimeSpan).FullName, (SqlDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (SqlDbType.Time, "time", "time",false, true, null) }, + { typeof(DateTime).FullName, (SqlDbType.DateTime, "datetime", "datetime NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (SqlDbType.DateTime, "datetime", "datetime", false, true, null) }, + { typeof(DateTimeOffset).FullName, (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset NOT NULL", false, false, new DateTimeOffset(new DateTime(1970,1,1), TimeSpan.Zero)) },{ typeof(DateTimeOffset?).FullName, (SqlDbType.DateTimeOffset, "datetimeoffset", "datetimeoffset", false, true, null) }, - { typeof(Guid).FullName, (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier", false, true, null) }, - }; + { typeof(byte[]).FullName, (SqlDbType.VarBinary, "varbinary", "varbinary(255)", false, null, new byte[0]) }, + { typeof(string).FullName, (SqlDbType.NVarChar, "nvarchar", "nvarchar(255)", false, null, "") }, - public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) { - if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); - if (type.IsArray) return null; - var enumType = type.IsEnum ? type : null; - if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); - if (enumType != null) { - var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? - (SqlDbType.BigInt, "bigint", $"bigint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : - (SqlDbType.Int, "int", $"int{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); - if (_dicCsToDb.ContainsKey(type.FullName) == false) { - lock (_dicCsToDbLock) { - if (_dicCsToDb.ContainsKey(type.FullName) == false) - _dicCsToDb.Add(type.FullName, newItem); - } - } - return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); - } - return null; - } + { typeof(Guid).FullName, (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (SqlDbType.UniqueIdentifier, "uniqueidentifier", "uniqueidentifier", false, true, null) }, + }; - void AddOrUpdateMS_Description(StringBuilder sb, string schema, string table, string column, string comment) { - if (string.IsNullOrEmpty(comment)) { - sb.AppendFormat(@" + public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) + { + if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); + if (type.IsArray) return null; + var enumType = type.IsEnum ? type : null; + if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); + if (enumType != null) + { + var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? + (SqlDbType.BigInt, "bigint", $"bigint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : + (SqlDbType.Int, "int", $"int{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); + if (_dicCsToDb.ContainsKey(type.FullName) == false) + { + lock (_dicCsToDbLock) + { + if (_dicCsToDb.ContainsKey(type.FullName) == false) + _dicCsToDb.Add(type.FullName, newItem); + } + } + return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); + } + return null; + } + + void AddOrUpdateMS_Description(StringBuilder sb, string schema, string table, string column, string comment) + { + if (string.IsNullOrEmpty(comment)) + { + sb.AppendFormat(@" IF ((SELECT COUNT(1) from fn_listextendedproperty('MS_Description', 'SCHEMA', N'{0}', 'TABLE', N'{1}', @@ -76,9 +84,9 @@ IF ((SELECT COUNT(1) from fn_listextendedproperty('MS_Description', , @level1type = 'TABLE', @level1name = N'{1}' , @level2type = 'COLUMN', @level2name = N'{2}' ", schema.Replace("'", "''"), table.Replace("'", "''"), column.Replace("'", "''")); - return; - } - sb.AppendFormat(@" + return; + } + sb.AppendFormat(@" IF ((SELECT COUNT(1) from fn_listextendedproperty('MS_Description', 'SCHEMA', N'{0}', 'TABLE', N'{1}', @@ -93,96 +101,115 @@ ELSE , @level1type = 'TABLE', @level1name = N'{1}' , @level2type = 'COLUMN', @level2name = N'{2}' ", schema.Replace("'", "''"), table.Replace("'", "''"), column.Replace("'", "''"), comment?.Replace("'", "''") ?? ""); - } - public override string GetComparisonDDLStatements(params Type[] entityTypes) { - var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5)); - var database = conn.Value.Database; - Func ExecuteScalar = (db, sql) => { - if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(db); - try { - using (var cmd = conn.Value.CreateCommand()) { - cmd.CommandText = sql; - cmd.CommandType = CommandType.Text; - return cmd.ExecuteScalar(); - } - } finally { - if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(database); - } - }; - var sb = new StringBuilder(); - try { - foreach (var entityType in entityTypes) { - if (sb.Length > 0) sb.Append("\r\n"); - var tb = _commonUtils.GetTableByEntity(entityType); - if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); - if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); - var tbname = tb.DbName.Split(new[] { '.' }, 3); - if (tbname?.Length == 1) tbname = new[] { database, "dbo", tbname[0] }; - if (tbname?.Length == 2) tbname = new[] { database, tbname[0], tbname[1] }; + } + public override string GetComparisonDDLStatements(params Type[] entityTypes) + { + var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5)); + var database = conn.Value.Database; + Func ExecuteScalar = (db, sql) => + { + if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(db); + try + { + using (var cmd = conn.Value.CreateCommand()) + { + cmd.CommandText = sql; + cmd.CommandType = CommandType.Text; + return cmd.ExecuteScalar(); + } + } + finally + { + if (string.Compare(database, db) != 0) conn.Value.ChangeDatabase(database); + } + }; + var sb = new StringBuilder(); + try + { + foreach (var entityType in entityTypes) + { + if (sb.Length > 0) sb.Append("\r\n"); + var tb = _commonUtils.GetTableByEntity(entityType); + if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); + if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); + var tbname = tb.DbName.Split(new[] { '.' }, 3); + if (tbname?.Length == 1) tbname = new[] { database, "dbo", tbname[0] }; + if (tbname?.Length == 2) tbname = new[] { database, tbname[0], tbname[1] }; - var tboldname = tb.DbOldName?.Split(new[] { '.' }, 3); //旧表名 - if (tboldname?.Length == 1) tboldname = new[] { database, "dbo", tboldname[0] }; - if (tboldname?.Length == 2) tboldname = new[] { database, tboldname[0], tboldname[1] }; + var tboldname = tb.DbOldName?.Split(new[] { '.' }, 3); //旧表名 + if (tboldname?.Length == 1) tboldname = new[] { database, "dbo", tboldname[0] }; + if (tboldname?.Length == 2) tboldname = new[] { database, tboldname[0], tboldname[1] }; - if (string.Compare(tbname[0], database, true) != 0 && ExecuteScalar(database, $" select 1 from sys.databases where name='{tbname[0]}'") == null) //创建数据库 - ExecuteScalar(database, $"if not exists(select 1 from sys.databases where name='{tbname[0]}')\r\n\tcreate database [{tbname[0]}];"); - if (string.Compare(tbname[1], "dbo", true) != 0 && ExecuteScalar(tbname[0], $" select 1 from sys.schemas where name='{tbname[1]}'") == null) //创建模式 - ExecuteScalar(tbname[0], $"create schema [{tbname[1]}] authorization [dbo]"); + if (string.Compare(tbname[0], database, true) != 0 && ExecuteScalar(database, $" select 1 from sys.databases where name='{tbname[0]}'") == null) //创建数据库 + ExecuteScalar(database, $"if not exists(select 1 from sys.databases where name='{tbname[0]}')\r\n\tcreate database [{tbname[0]}];"); + if (string.Compare(tbname[1], "dbo", true) != 0 && ExecuteScalar(tbname[0], $" select 1 from sys.schemas where name='{tbname[1]}'") == null) //创建模式 + ExecuteScalar(tbname[0], $"create schema [{tbname[1]}] authorization [dbo]"); - var sbalter = new StringBuilder(); - var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 - if (ExecuteScalar(tbname[0], $" select 1 from dbo.sysobjects where id = object_id(N'[{tbname[1]}].[{tbname[2]}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1") == null) { //表不存在 - if (tboldname != null) { - if (string.Compare(tboldname[0], tbname[0], true) != 0 && ExecuteScalar(database, $" select 1 from sys.databases where name='{tboldname[0]}'") == null || - string.Compare(tboldname[1], tbname[1], true) != 0 && ExecuteScalar(tboldname[0], $" select 1 from sys.schemas where name='{tboldname[1]}'") == null || - ExecuteScalar(tboldname[0], $" select 1 from dbo.sysobjects where id = object_id(N'[{tboldname[1]}].[{tboldname[2]}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1") == null) - //数据库或模式或表不存在 - tboldname = null; - } - if (tboldname == null) { - //创建新表 - sb.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(";\r\nCREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append(" ( "); - var pkidx = 0; - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); - if (tbcol.Attribute.IsPrimary == true) { - if (tb.Primarys.Length > 1) { - if (pkidx == tb.Primarys.Length - 1) - sb.Append(" primary key (").Append(string.Join(", ", tb.Primarys.Select(a => _commonUtils.QuoteSqlName(a.Attribute.Name)))).Append(")"); - } else - sb.Append(" primary key"); - pkidx++; - } - sb.Append(","); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n"); - //备注 - foreach (var tbcol in tb.Columns.Values) { - if (string.IsNullOrEmpty(tbcol.Comment) == false) - AddOrUpdateMS_Description(sb, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment); - } - continue; - } - //如果新表,旧表在一个数据库和模式下,直接修改表名 - if (string.Compare(tbname[0], tboldname[0], true) == 0 && - string.Compare(tbname[1], tboldname[1], true) == 0) - sbalter.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(_commonUtils.FormatSql(";\r\nEXEC sp_rename {0}, {1};\r\n", _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}.{tboldname[2]}"), tbname[2])); - else { - //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 - istmpatler = true; - } - } else - tboldname = null; //如果新表已经存在,不走改表名逻辑 + var sbalter = new StringBuilder(); + var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 + if (ExecuteScalar(tbname[0], $" select 1 from dbo.sysobjects where id = object_id(N'[{tbname[1]}].[{tbname[2]}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1") == null) + { //表不存在 + if (tboldname != null) + { + if (string.Compare(tboldname[0], tbname[0], true) != 0 && ExecuteScalar(database, $" select 1 from sys.databases where name='{tboldname[0]}'") == null || + string.Compare(tboldname[1], tbname[1], true) != 0 && ExecuteScalar(tboldname[0], $" select 1 from sys.schemas where name='{tboldname[1]}'") == null || + ExecuteScalar(tboldname[0], $" select 1 from dbo.sysobjects where id = object_id(N'[{tboldname[1]}].[{tboldname[2]}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1") == null) + //数据库或模式或表不存在 + tboldname = null; + } + if (tboldname == null) + { + //创建新表 + sb.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(";\r\nCREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append(" ( "); + var pkidx = 0; + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); + sb.Append(tbcol.Attribute.DbType); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); + if (tbcol.Attribute.IsPrimary == true) + { + if (tb.Primarys.Length > 1) + { + if (pkidx == tb.Primarys.Length - 1) + sb.Append(" primary key (").Append(string.Join(", ", tb.Primarys.Select(a => _commonUtils.QuoteSqlName(a.Attribute.Name)))).Append(")"); + } + else + sb.Append(" primary key"); + pkidx++; + } + sb.Append(","); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n"); + //备注 + foreach (var tbcol in tb.Columns.Values) + { + if (string.IsNullOrEmpty(tbcol.Comment) == false) + AddOrUpdateMS_Description(sb, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment); + } + continue; + } + //如果新表,旧表在一个数据库和模式下,直接修改表名 + if (string.Compare(tbname[0], tboldname[0], true) == 0 && + string.Compare(tbname[1], tboldname[1], true) == 0) + sbalter.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(_commonUtils.FormatSql(";\r\nEXEC sp_rename {0}, {1};\r\n", _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}.{tboldname[2]}"), tbname[2])); + else + { + //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 + istmpatler = true; + } + } + else + tboldname = null; //如果新表已经存在,不走改表名逻辑 - //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 - var sql = string.Format(@" + //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 + var sql = string.Format(@" use [{0}]; select a.name 'Column' @@ -203,45 +230,51 @@ left join sys.tables d on d.object_id = a.object_id left join sys.schemas e on e.schema_id = d.schema_id where a.object_id in (object_id(N'[{1}].[{2}]')); use " + database, tboldname ?? tbname); - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => new { - column = string.Concat(a[0]), - sqlType = string.Concat(a[1]), - is_nullable = string.Concat(a[2]) == "1", - is_identity = string.Concat(a[3]) == "1", - comment = string.Concat(a[4]) - }, StringComparer.CurrentCultureIgnoreCase); + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a => new + { + column = string.Concat(a[0]), + sqlType = string.Concat(a[1]), + is_nullable = string.Concat(a[2]) == "1", + is_identity = string.Concat(a[3]) == "1", + comment = string.Concat(a[4]) + }, StringComparer.CurrentCultureIgnoreCase); - if (istmpatler == false) { - foreach (var tbcol in tb.Columns.Values) { - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? ""); - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false || - tbcol.Attribute.IsNullable != tbstructcol.is_nullable || - tbcol.Attribute.IsIdentity != tbstructcol.is_identity) { - istmpatler = true; - break; - } - if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) - //修改列名 - sbalter.Append(_commonUtils.FormatSql("EXEC sp_rename {0}, {1}, 'COLUMN';\r\n", $"{tbname[0]}.{tbname[1]}.{tbname[2]}.{tbstructcol.column}", tbcol.Attribute.Name)); - if (isCommentChanged) - //修改备备注 - AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment); - continue; - } - //添加列 - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" identity(1,1)"); - if (tbcol.Attribute.IsNullable == false) { - var addcoldbdefault = tbcol.Attribute.DbDefautValue; - if (addcoldbdefault != null) sbalter.Append(_commonUtils.FormatSql(" default({0})", addcoldbdefault)); - } - sbalter.Append(";\r\n"); - if (string.IsNullOrEmpty(tbcol.Comment) == false) AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment); - } - var dsuksql = string.Format(@" + if (istmpatler == false) + { + foreach (var tbcol in tb.Columns.Values) + { + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? ""); + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false || + tbcol.Attribute.IsNullable != tbstructcol.is_nullable || + tbcol.Attribute.IsIdentity != tbstructcol.is_identity) + { + istmpatler = true; + break; + } + if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) + //修改列名 + sbalter.Append(_commonUtils.FormatSql("EXEC sp_rename {0}, {1}, 'COLUMN';\r\n", $"{tbname[0]}.{tbname[1]}.{tbname[2]}.{tbstructcol.column}", tbcol.Attribute.Name)); + if (isCommentChanged) + //修改备备注 + AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment); + continue; + } + //添加列 + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sbalter.Append(" identity(1,1)"); + if (tbcol.Attribute.IsNullable == false) + { + var addcoldbdefault = tbcol.Attribute.DbDefautValue; + if (addcoldbdefault != null) sbalter.Append(_commonUtils.FormatSql(" default({0})", addcoldbdefault)); + } + sbalter.Append(";\r\n"); + if (string.IsNullOrEmpty(tbcol.Comment) == false) AddOrUpdateMS_Description(sbalter, tbname[1], tbname[2], tbcol.Attribute.Name, tbcol.Comment); + } + var dsuksql = string.Format(@" use [{0}]; select c.name @@ -252,111 +285,130 @@ left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_ left join sys.key_constraints d on d.parent_object_id = b.object_id and d.unique_index_id = b.index_id where a.object_id in (object_id(N'[{1}].[{2}]')) and b.is_unique = 1; use " + database, tboldname ?? tbname); - var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) }); - foreach (var uk in tb.Uniques) { - if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; - var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); - if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) { - if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n"); - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n"); - } - } - } - if (istmpatler == false) { - sb.Append(sbalter).Append("\r\nuse " + database); - continue; - } - //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 - bool idents = false; - var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}.{tboldname[2]}"); - var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.FreeSqlTmp_{tbname[2]}"); - sb.Append("BEGIN TRANSACTION\r\n") - .Append("SET QUOTED_IDENTIFIER ON\r\n") - .Append("SET ARITHABORT ON\r\n") - .Append("SET NUMERIC_ROUNDABORT OFF\r\n") - .Append("SET CONCAT_NULL_YIELDS_NULL ON\r\n") - .Append("SET ANSI_NULLS ON\r\n") - .Append("SET ANSI_PADDING ON\r\n") - .Append("SET ANSI_WARNINGS ON\r\n") - .Append("COMMIT\r\n"); - sb.Append("BEGIN TRANSACTION;\r\n"); - //创建临时表 - sb.Append("CREATE TABLE ").Append(tmptablename).Append(" ( "); - var pkidx2 = 0; - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); - if (tbcol.Attribute.IsPrimary == true) { - if (tb.Primarys.Length > 1) { - if (pkidx2 == tb.Primarys.Length - 1) - sb.Append(" primary key (").Append(string.Join(", ", tb.Primarys.Select(a => _commonUtils.QuoteSqlName(a.Attribute.Name)))).Append(")"); - } else - sb.Append(" primary key"); - pkidx2++; - } - sb.Append(","); - idents = idents || tbcol.Attribute.IsIdentity == true; - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n"); - //备注 - foreach (var tbcol in tb.Columns.Values) { - if (string.IsNullOrEmpty(tbcol.Comment) == false) - AddOrUpdateMS_Description(sb, tbname[1], $"FreeSqlTmp_{tbname[2]}", tbcol.Attribute.Name, tbcol.Comment); - } - sb.Append("ALTER TABLE ").Append(tmptablename).Append(" SET (LOCK_ESCALATION = TABLE);\r\n"); - if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" ON;\r\n"); - sb.Append("IF EXISTS(SELECT 1 FROM ").Append(tablename).Append(")\r\n"); - sb.Append("\tEXEC('INSERT INTO ").Append(tmptablename).Append(" ("); - foreach (var tbcol in tb.Columns.Values) - sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append(")\r\n\t\tSELECT "); - foreach (var tbcol in tb.Columns.Values) { - var insertvalue = "NULL"; - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) - insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; - if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"isnull({insertvalue},{_commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol))})"; - } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol)); - sb.Append(insertvalue.Replace("'", "''")).Append(", "); - } - sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(" WITH (HOLDLOCK TABLOCKX)');\r\n"); - if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" OFF;\r\n"); - sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n"); - sb.Append("EXECUTE sp_rename N'").Append(tmptablename).Append("', N'").Append(tbname[2]).Append("', 'OBJECT';\r\n"); - sb.Append("COMMIT;\r\n"); - } - return sb.Length == 0 ? null : sb.ToString(); - } finally { - try { - conn.Value.ChangeDatabase(database); - _orm.Ado.MasterPool.Return(conn); - } catch { - _orm.Ado.MasterPool.Return(conn, true); - } - } - } - object GetTransferDbDefaultValue(ColumnInfo col) { - var ddv = col.Attribute.DbDefautValue; - if (ddv == null) return ddv; - if (ddv is DateTime || ddv is DateTime?) { - var dt = (DateTime)ddv; - if (col.Attribute.DbType.Contains("SMALLDATETIME") && dt < new DateTime(1900, 1, 1)) ddv = new DateTime(1900, 1, 1); - else if (col.Attribute.DbType.Contains("DATETIME") && dt < new DateTime(1753, 1, 1)) ddv = new DateTime(1753, 1, 1); - else if (col.Attribute.DbType.Contains("DATE") && dt < new DateTime(0001, 1, 1)) ddv = new DateTime(0001, 1, 1); - } - return ddv; - } - } + var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) }); + foreach (var uk in tb.Uniques) + { + if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; + var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); + if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) + { + if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n"); + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n"); + } + } + } + if (istmpatler == false) + { + sb.Append(sbalter).Append("\r\nuse " + database); + continue; + } + //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 + bool idents = false; + var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}.{tboldname[2]}"); + var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.FreeSqlTmp_{tbname[2]}"); + sb.Append("BEGIN TRANSACTION\r\n") + .Append("SET QUOTED_IDENTIFIER ON\r\n") + .Append("SET ARITHABORT ON\r\n") + .Append("SET NUMERIC_ROUNDABORT OFF\r\n") + .Append("SET CONCAT_NULL_YIELDS_NULL ON\r\n") + .Append("SET ANSI_NULLS ON\r\n") + .Append("SET ANSI_PADDING ON\r\n") + .Append("SET ANSI_WARNINGS ON\r\n") + .Append("COMMIT\r\n"); + sb.Append("BEGIN TRANSACTION;\r\n"); + //创建临时表 + sb.Append("CREATE TABLE ").Append(tmptablename).Append(" ( "); + var pkidx2 = 0; + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); + sb.Append(tbcol.Attribute.DbType); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("identity", StringComparison.CurrentCultureIgnoreCase) == -1) sb.Append(" identity(1,1)"); + if (tbcol.Attribute.IsPrimary == true) + { + if (tb.Primarys.Length > 1) + { + if (pkidx2 == tb.Primarys.Length - 1) + sb.Append(" primary key (").Append(string.Join(", ", tb.Primarys.Select(a => _commonUtils.QuoteSqlName(a.Attribute.Name)))).Append(")"); + } + else + sb.Append(" primary key"); + pkidx2++; + } + sb.Append(","); + idents = idents || tbcol.Attribute.IsIdentity == true; + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n"); + //备注 + foreach (var tbcol in tb.Columns.Values) + { + if (string.IsNullOrEmpty(tbcol.Comment) == false) + AddOrUpdateMS_Description(sb, tbname[1], $"FreeSqlTmp_{tbname[2]}", tbcol.Attribute.Name, tbcol.Comment); + } + sb.Append("ALTER TABLE ").Append(tmptablename).Append(" SET (LOCK_ESCALATION = TABLE);\r\n"); + if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" ON;\r\n"); + sb.Append("IF EXISTS(SELECT 1 FROM ").Append(tablename).Append(")\r\n"); + sb.Append("\tEXEC('INSERT INTO ").Append(tmptablename).Append(" ("); + foreach (var tbcol in tb.Columns.Values) + sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append(")\r\n\t\tSELECT "); + foreach (var tbcol in tb.Columns.Values) + { + var insertvalue = "NULL"; + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) + insertvalue = $"cast({insertvalue} as {tbcol.Attribute.DbType.Split(' ').First()})"; + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) + insertvalue = $"isnull({insertvalue},{_commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol))})"; + } + else if (tbcol.Attribute.IsNullable == false) + insertvalue = _commonUtils.FormatSql("{0}", GetTransferDbDefaultValue(tbcol)); + sb.Append(insertvalue.Replace("'", "''")).Append(", "); + } + sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(" WITH (HOLDLOCK TABLOCKX)');\r\n"); + if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" OFF;\r\n"); + sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n"); + sb.Append("EXECUTE sp_rename N'").Append(tmptablename).Append("', N'").Append(tbname[2]).Append("', 'OBJECT';\r\n"); + sb.Append("COMMIT;\r\n"); + } + return sb.Length == 0 ? null : sb.ToString(); + } + finally + { + try + { + conn.Value.ChangeDatabase(database); + _orm.Ado.MasterPool.Return(conn); + } + catch + { + _orm.Ado.MasterPool.Return(conn, true); + } + } + } + object GetTransferDbDefaultValue(ColumnInfo col) + { + var ddv = col.Attribute.DbDefautValue; + if (ddv == null) return ddv; + if (ddv is DateTime || ddv is DateTime?) + { + var dt = (DateTime)ddv; + if (col.Attribute.DbType.Contains("SMALLDATETIME") && dt < new DateTime(1900, 1, 1)) ddv = new DateTime(1900, 1, 1); + else if (col.Attribute.DbType.Contains("DATETIME") && dt < new DateTime(1753, 1, 1)) ddv = new DateTime(1753, 1, 1); + else if (col.Attribute.DbType.Contains("DATE") && dt < new DateTime(0001, 1, 1)) ddv = new DateTime(0001, 1, 1); + } + return ddv; + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerDbFirst.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerDbFirst.cs index 56405a7e..35b91bee 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerDbFirst.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerDbFirst.cs @@ -6,118 +6,127 @@ using System.Data; using System.Linq; using System.Text.RegularExpressions; -namespace FreeSql.SqlServer { - class SqlServerDbFirst : IDbFirst { - IFreeSql _orm; - protected CommonUtils _commonUtils; - protected CommonExpression _commonExpression; - public SqlServerDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) { - _orm = orm; - _commonUtils = commonUtils; - _commonExpression = commonExpression; - } +namespace FreeSql.SqlServer +{ + class SqlServerDbFirst : IDbFirst + { + IFreeSql _orm; + protected CommonUtils _commonUtils; + protected CommonExpression _commonExpression; + public SqlServerDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + { + _orm = orm; + _commonUtils = commonUtils; + _commonExpression = commonExpression; + } - public int GetDbType(DbColumnInfo column) => (int)GetSqlDbType(column); - SqlDbType GetSqlDbType(DbColumnInfo column) { - switch (column.DbTypeText.ToLower()) { - case "bit": return SqlDbType.Bit; - case "tinyint": return SqlDbType.TinyInt; - case "smallint": return SqlDbType.SmallInt; - case "int": return SqlDbType.Int; - case "bigint": return SqlDbType.BigInt; - case "numeric": - case "decimal": return SqlDbType.Decimal; - case "smallmoney": return SqlDbType.SmallMoney; - case "money": return SqlDbType.Money; - case "float": return SqlDbType.Float; - case "real": return SqlDbType.Real; - case "date": return SqlDbType.Date; - case "datetime": - case "datetime2": return SqlDbType.DateTime; - case "datetimeoffset": return SqlDbType.DateTimeOffset; - case "smalldatetime": return SqlDbType.SmallDateTime; - case "time": return SqlDbType.Time; - case "char": return SqlDbType.Char; - case "varchar": return SqlDbType.VarChar; - case "text": return SqlDbType.Text; - case "nchar": return SqlDbType.NChar; - case "nvarchar": return SqlDbType.NVarChar; - case "ntext": return SqlDbType.NText; - case "binary": return SqlDbType.Binary; - case "varbinary": return SqlDbType.VarBinary; - case "image": return SqlDbType.Image; - case "timestamp": return SqlDbType.Timestamp; - case "uniqueidentifier": return SqlDbType.UniqueIdentifier; - default: return SqlDbType.Variant; - } - } + public int GetDbType(DbColumnInfo column) => (int)GetSqlDbType(column); + SqlDbType GetSqlDbType(DbColumnInfo column) + { + switch (column.DbTypeText.ToLower()) + { + case "bit": return SqlDbType.Bit; + case "tinyint": return SqlDbType.TinyInt; + case "smallint": return SqlDbType.SmallInt; + case "int": return SqlDbType.Int; + case "bigint": return SqlDbType.BigInt; + case "numeric": + case "decimal": return SqlDbType.Decimal; + case "smallmoney": return SqlDbType.SmallMoney; + case "money": return SqlDbType.Money; + case "float": return SqlDbType.Float; + case "real": return SqlDbType.Real; + case "date": return SqlDbType.Date; + case "datetime": + case "datetime2": return SqlDbType.DateTime; + case "datetimeoffset": return SqlDbType.DateTimeOffset; + case "smalldatetime": return SqlDbType.SmallDateTime; + case "time": return SqlDbType.Time; + case "char": return SqlDbType.Char; + case "varchar": return SqlDbType.VarChar; + case "text": return SqlDbType.Text; + case "nchar": return SqlDbType.NChar; + case "nvarchar": return SqlDbType.NVarChar; + case "ntext": return SqlDbType.NText; + case "binary": return SqlDbType.Binary; + case "varbinary": return SqlDbType.VarBinary; + case "image": return SqlDbType.Image; + case "timestamp": return SqlDbType.Timestamp; + case "uniqueidentifier": return SqlDbType.UniqueIdentifier; + default: return SqlDbType.Variant; + } + } - static readonly Dictionary _dicDbToCs = new Dictionary() { - { (int)SqlDbType.Bit, ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, + static readonly Dictionary _dicDbToCs = new Dictionary() { + { (int)SqlDbType.Bit, ("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, - { (int)SqlDbType.TinyInt, ("(byte?)", "byte.Parse({0})", "{0}.ToString()", "byte?", typeof(byte), typeof(byte?), "{0}.Value", "GetByte") }, - { (int)SqlDbType.SmallInt, ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, - { (int)SqlDbType.Int, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, - { (int)SqlDbType.BigInt, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, + { (int)SqlDbType.TinyInt, ("(byte?)", "byte.Parse({0})", "{0}.ToString()", "byte?", typeof(byte), typeof(byte?), "{0}.Value", "GetByte") }, + { (int)SqlDbType.SmallInt, ("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, + { (int)SqlDbType.Int, ("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, + { (int)SqlDbType.BigInt, ("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, - { (int)SqlDbType.SmallMoney, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, - { (int)SqlDbType.Money, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, - { (int)SqlDbType.Decimal, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, - { (int)SqlDbType.Float, ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, - { (int)SqlDbType.Real, ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, + { (int)SqlDbType.SmallMoney, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, + { (int)SqlDbType.Money, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, + { (int)SqlDbType.Decimal, ("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, + { (int)SqlDbType.Float, ("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, + { (int)SqlDbType.Real, ("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, - { (int)SqlDbType.Time, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, - { (int)SqlDbType.Date, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)SqlDbType.DateTime, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)SqlDbType.DateTime2, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)SqlDbType.SmallDateTime, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, - { (int)SqlDbType.DateTimeOffset, ("(DateTimeOffset?)", "new DateTimeOffset(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTimeOffset), typeof(DateTimeOffset?), "{0}.Value", "GetDateTimeOffset") }, + { (int)SqlDbType.Time, ("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, + { (int)SqlDbType.Date, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)SqlDbType.DateTime, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)SqlDbType.DateTime2, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)SqlDbType.SmallDateTime, ("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, + { (int)SqlDbType.DateTimeOffset, ("(DateTimeOffset?)", "new DateTimeOffset(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTimeOffset), typeof(DateTimeOffset?), "{0}.Value", "GetDateTimeOffset") }, - { (int)SqlDbType.Binary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)SqlDbType.VarBinary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)SqlDbType.Image, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)SqlDbType.Timestamp, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)SqlDbType.Binary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)SqlDbType.VarBinary, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)SqlDbType.Image, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, + { (int)SqlDbType.Timestamp, ("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, - { (int)SqlDbType.Char, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)SqlDbType.VarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)SqlDbType.Text, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)SqlDbType.NChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)SqlDbType.NVarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)SqlDbType.NText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)SqlDbType.Char, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)SqlDbType.VarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)SqlDbType.Text, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)SqlDbType.NChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)SqlDbType.NVarChar, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, + { (int)SqlDbType.NText, ("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, - { (int)SqlDbType.UniqueIdentifier, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}.Value", "GetGuid") }, - }; + { (int)SqlDbType.UniqueIdentifier, ("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid?", typeof(Guid), typeof(Guid?), "{0}.Value", "GetGuid") }, + }; - public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; - public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csParse : null; - public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csStringify : null; - public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; - public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeInfo : null; - public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeValue : null; - public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.dataReaderMethod : null; + public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; + public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csParse : null; + public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csStringify : null; + public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; + public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeInfo : null; + public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeValue : null; + public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.dataReaderMethod : null; - public List GetDatabases() { - var sql = @" select name from sys.databases where name not in ('master','tempdb','model','msdb')"; - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); - } + public List GetDatabases() + { + var sql = @" select name from sys.databases where name not in ('master','tempdb','model','msdb')"; + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + return ds.Select(a => a.FirstOrDefault()?.ToString()).ToList(); + } - public List GetTablesByDatabase(params string[] database) { - var olddatabase = ""; - using (var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5))) { - olddatabase = conn.Value.Database; - } - var dbs = database == null || database.Any() == false ? new[] { olddatabase } : database; - var tables = new List(); + public List GetTablesByDatabase(params string[] database) + { + var olddatabase = ""; + using (var conn = _orm.Ado.MasterPool.Get(TimeSpan.FromSeconds(5))) + { + olddatabase = conn.Value.Database; + } + var dbs = database == null || database.Any() == false ? new[] { olddatabase } : database; + var tables = new List(); - foreach (var db in dbs) { - if (string.IsNullOrEmpty(db)) continue; + foreach (var db in dbs) + { + if (string.IsNullOrEmpty(db)) continue; - var loc1 = new List(); - var loc2 = new Dictionary(); - var loc3 = new Dictionary>(); + var loc1 = new List(); + var loc2 = new Dictionary(); + var loc3 = new Dictionary>(); - var sql = $@" + var sql = $@" use [{db}]; select a.Object_id @@ -154,34 +163,36 @@ order by type desc, b.name, a.name ; use [{olddatabase}]; "; - var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var loc6 = new List(); - var loc66 = new List(); - foreach (object[] row in ds) { - int object_id = int.Parse(string.Concat(row[0])); - var owner = string.Concat(row[1]); - var table = string.Concat(row[2]); - var comment = string.Concat(row[3]); - Enum.TryParse(string.Concat(row[4]), out var type); - loc2.Add(object_id, new DbTableInfo { Id = object_id.ToString(), Schema = owner, Name = table, Comment = comment, Type = type }); - loc3.Add(object_id, new Dictionary()); - switch (type) { - case DbTableType.VIEW: - case DbTableType.TABLE: - loc6.Add(object_id); - break; - case DbTableType.StoreProcedure: - loc66.Add(object_id); - break; - } - } - if (loc6.Count == 0) return loc1; - var loc8 = string.Join(",", loc6.Select(a => string.Concat(a))); - var loc88 = string.Join(",", loc66.Select(a => string.Concat(a))); + var loc6 = new List(); + var loc66 = new List(); + foreach (object[] row in ds) + { + int object_id = int.Parse(string.Concat(row[0])); + var owner = string.Concat(row[1]); + var table = string.Concat(row[2]); + var comment = string.Concat(row[3]); + Enum.TryParse(string.Concat(row[4]), out var type); + loc2.Add(object_id, new DbTableInfo { Id = object_id.ToString(), Schema = owner, Name = table, Comment = comment, Type = type }); + loc3.Add(object_id, new Dictionary()); + switch (type) + { + case DbTableType.VIEW: + case DbTableType.TABLE: + loc6.Add(object_id); + break; + case DbTableType.StoreProcedure: + loc66.Add(object_id); + break; + } + } + if (loc6.Count == 0) return loc1; + var loc8 = string.Join(",", loc6.Select(a => string.Concat(a))); + var loc88 = string.Join(",", loc66.Select(a => string.Concat(a))); - var tsql_place = @" + var tsql_place = @" select isnull(e.name,'') + '.' + isnull(d.name,'') @@ -207,51 +218,54 @@ left join sys.tables d on d.object_id = a.object_id left join sys.schemas e on e.schema_id = d.schema_id where a.object_id in ({1}) "; - sql = string.Format(tsql_place, @" + sql = string.Format(tsql_place, @" ,a.is_nullable 'IsNullable' ,a.is_identity 'IsIdentity' from sys.columns", loc8); - if (loc88.Length > 0) { - sql += "union all" + - string.Format(tsql_place.Replace( - "left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.column_id", - "left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.parameter_id"), @" + if (loc88.Length > 0) + { + sql += "union all" + + string.Format(tsql_place.Replace( + "left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.column_id", + "left join sys.extended_properties AS c ON c.major_id = a.object_id AND c.minor_id = a.parameter_id"), @" ,cast(0 as bit) 'IsNullable' ,a.is_output 'IsIdentity' from sys.parameters", loc88); - } - sql = $"use [{db}];{sql};use [{olddatabase}]; "; - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + } + sql = $"use [{db}];{sql};use [{olddatabase}]; "; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - foreach (object[] row in ds) { - var table_id = string.Concat(row[0]); - var object_id = int.Parse(string.Concat(row[1])); - var column = string.Concat(row[2]); - var type = string.Concat(row[3]); - var max_length = int.Parse(string.Concat(row[4])); - var sqlType = string.Concat(row[5]); - var comment = string.Concat(row[6]); - var is_nullable = bool.Parse(string.Concat(row[7])); - var is_identity = bool.Parse(string.Concat(row[8])); - if (max_length == 0) max_length = -1; + foreach (object[] row in ds) + { + var table_id = string.Concat(row[0]); + var object_id = int.Parse(string.Concat(row[1])); + var column = string.Concat(row[2]); + var type = string.Concat(row[3]); + var max_length = int.Parse(string.Concat(row[4])); + var sqlType = string.Concat(row[5]); + var comment = string.Concat(row[6]); + var is_nullable = bool.Parse(string.Concat(row[7])); + var is_identity = bool.Parse(string.Concat(row[8])); + if (max_length == 0) max_length = -1; - loc3[object_id].Add(column, new DbColumnInfo { - Name = column, - MaxLength = max_length, - IsIdentity = is_identity, - IsNullable = is_nullable, - IsPrimary = false, - DbTypeText = type, - DbTypeTextFull = sqlType, - Table = loc2[object_id], - Coment = comment - }); - loc3[object_id][column].DbType = this.GetDbType(loc3[object_id][column]); - loc3[object_id][column].CsType = this.GetCsTypeInfo(loc3[object_id][column]); - } + loc3[object_id].Add(column, new DbColumnInfo + { + Name = column, + MaxLength = max_length, + IsIdentity = is_identity, + IsNullable = is_nullable, + IsPrimary = false, + DbTypeText = type, + DbTypeTextFull = sqlType, + Table = loc2[object_id], + Coment = comment + }); + loc3[object_id][column].DbType = this.GetDbType(loc3[object_id][column]); + loc3[object_id][column].CsType = this.GetCsTypeInfo(loc3[object_id][column]); + } - sql = $@" + sql = $@" use [{db}]; select a.object_id 'Object_id' @@ -269,51 +283,56 @@ where a.object_id in ({loc8}) ; use [{olddatabase}]; "; - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var indexColumns = new Dictionary>>(); - var uniqueColumns = new Dictionary>>(); - foreach (object[] row in ds) { - int object_id = int.Parse(string.Concat(row[0])); - string column = string.Concat(row[1]); - string index_id = string.Concat(row[2]); - bool is_unique = bool.Parse(string.Concat(row[3])); - bool is_primary_key = bool.Parse(string.Concat(row[4])); - bool is_clustered = bool.Parse(string.Concat(row[5])); - int is_desc = int.Parse(string.Concat(row[6])); + var indexColumns = new Dictionary>>(); + var uniqueColumns = new Dictionary>>(); + foreach (object[] row in ds) + { + int object_id = int.Parse(string.Concat(row[0])); + string column = string.Concat(row[1]); + string index_id = string.Concat(row[2]); + bool is_unique = bool.Parse(string.Concat(row[3])); + bool is_primary_key = bool.Parse(string.Concat(row[4])); + bool is_clustered = bool.Parse(string.Concat(row[5])); + int is_desc = int.Parse(string.Concat(row[6])); - if (loc3.ContainsKey(object_id) == false || loc3[object_id].ContainsKey(column) == false) continue; - DbColumnInfo loc9 = loc3[object_id][column]; - if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; + if (loc3.ContainsKey(object_id) == false || loc3[object_id].ContainsKey(column) == false) continue; + DbColumnInfo loc9 = loc3[object_id][column]; + if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; - Dictionary> loc10 = null; - List loc11 = null; - if (!indexColumns.TryGetValue(object_id, out loc10)) - indexColumns.Add(object_id, loc10 = new Dictionary>()); - if (!loc10.TryGetValue(index_id, out loc11)) - loc10.Add(index_id, loc11 = new List()); - loc11.Add(loc9); - if (is_unique && !is_primary_key) { - if (!uniqueColumns.TryGetValue(object_id, out loc10)) - uniqueColumns.Add(object_id, loc10 = new Dictionary>()); - if (!loc10.TryGetValue(index_id, out loc11)) - loc10.Add(index_id, loc11 = new List()); - loc11.Add(loc9); - } - } - foreach (var object_id in indexColumns.Keys) { - foreach (var column in indexColumns[object_id]) - loc2[object_id].IndexesDict.Add(column.Key, column.Value); - } - foreach (var object_id in uniqueColumns.Keys) { - foreach (var column in uniqueColumns[object_id]) { - column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); - loc2[object_id].UniquesDict.Add(column.Key, column.Value); - } - } + Dictionary> loc10 = null; + List loc11 = null; + if (!indexColumns.TryGetValue(object_id, out loc10)) + indexColumns.Add(object_id, loc10 = new Dictionary>()); + if (!loc10.TryGetValue(index_id, out loc11)) + loc10.Add(index_id, loc11 = new List()); + loc11.Add(loc9); + if (is_unique && !is_primary_key) + { + if (!uniqueColumns.TryGetValue(object_id, out loc10)) + uniqueColumns.Add(object_id, loc10 = new Dictionary>()); + if (!loc10.TryGetValue(index_id, out loc11)) + loc10.Add(index_id, loc11 = new List()); + loc11.Add(loc9); + } + } + foreach (var object_id in indexColumns.Keys) + { + foreach (var column in indexColumns[object_id]) + loc2[object_id].IndexesDict.Add(column.Key, column.Value); + } + foreach (var object_id in uniqueColumns.Keys) + { + foreach (var column in uniqueColumns[object_id]) + { + column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); + loc2[object_id].UniquesDict.Add(column.Key, column.Value); + } + } - sql = $@" + sql = $@" use [{db}]; select b.object_id 'Object_id' @@ -333,86 +352,99 @@ where b.object_id in ({loc8}) ; use [{olddatabase}]; "; - ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); - if (ds == null) return loc1; + ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); + if (ds == null) return loc1; - var fkColumns = new Dictionary>(); - foreach (object[] row in ds) { - int object_id, referenced_object_id; - int.TryParse(string.Concat(row[0]), out object_id); - var column = string.Concat(row[1]); - string fk_id = string.Concat(row[2]); - int.TryParse(string.Concat(row[3]), out referenced_object_id); - var is_foreign_key = bool.Parse(string.Concat(row[4])); - var referenced_column = string.Concat(row[5]); - var referenced_db = string.Concat(row[6]); - var referenced_table = string.Concat(row[7]); - DbColumnInfo loc9 = loc3[object_id][column]; - DbTableInfo loc10 = null; - DbColumnInfo loc11 = null; - bool isThisSln = referenced_object_id != 0; + var fkColumns = new Dictionary>(); + foreach (object[] row in ds) + { + int object_id, referenced_object_id; + int.TryParse(string.Concat(row[0]), out object_id); + var column = string.Concat(row[1]); + string fk_id = string.Concat(row[2]); + int.TryParse(string.Concat(row[3]), out referenced_object_id); + var is_foreign_key = bool.Parse(string.Concat(row[4])); + var referenced_column = string.Concat(row[5]); + var referenced_db = string.Concat(row[6]); + var referenced_table = string.Concat(row[7]); + DbColumnInfo loc9 = loc3[object_id][column]; + DbTableInfo loc10 = null; + DbColumnInfo loc11 = null; + bool isThisSln = referenced_object_id != 0; - if (isThisSln) { - loc10 = loc2[referenced_object_id]; - loc11 = loc3[referenced_object_id][referenced_column]; - } else { + if (isThisSln) + { + loc10 = loc2[referenced_object_id]; + loc11 = loc3[referenced_object_id][referenced_column]; + } + else + { - } - Dictionary loc12 = null; - DbForeignInfo loc13 = null; - if (!fkColumns.TryGetValue(object_id, out loc12)) - fkColumns.Add(object_id, loc12 = new Dictionary()); - if (!loc12.TryGetValue(fk_id, out loc13)) - loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[object_id], ReferencedTable = loc10 }); - loc13.Columns.Add(loc9); - loc13.ReferencedColumns.Add(loc11); - } - foreach (var table_id in fkColumns.Keys) - foreach (var fk in fkColumns[table_id]) - loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); + } + Dictionary loc12 = null; + DbForeignInfo loc13 = null; + if (!fkColumns.TryGetValue(object_id, out loc12)) + fkColumns.Add(object_id, loc12 = new Dictionary()); + if (!loc12.TryGetValue(fk_id, out loc13)) + loc12.Add(fk_id, loc13 = new DbForeignInfo { Table = loc2[object_id], ReferencedTable = loc10 }); + loc13.Columns.Add(loc9); + loc13.ReferencedColumns.Add(loc11); + } + foreach (var table_id in fkColumns.Keys) + foreach (var fk in fkColumns[table_id]) + loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value); - foreach (var table_id in loc3.Keys) { - foreach (var loc5 in loc3[table_id].Values) { - loc2[table_id].Columns.Add(loc5); - if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); - if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); - } - } - foreach (var loc4 in loc2.Values) { - if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) { - foreach (var loc5 in loc4.UniquesDict.First().Value) { - loc5.IsPrimary = true; - loc4.Primarys.Add(loc5); - } - } - loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); - loc4.Columns.Sort((c1, c2) => { - int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); - if (compare == 0) { - bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); - bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); - compare = b2.CompareTo(b1); - } - if (compare == 0) compare = c1.Name.CompareTo(c2.Name); - return compare; - }); - loc1.Add(loc4); - } - loc1.Sort((t1, t2) => { - var ret = t1.Schema.CompareTo(t2.Schema); - if (ret == 0) ret = t1.Name.CompareTo(t2.Name); - return ret; - }); + foreach (var table_id in loc3.Keys) + { + foreach (var loc5 in loc3[table_id].Values) + { + loc2[table_id].Columns.Add(loc5); + if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); + if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); + } + } + foreach (var loc4 in loc2.Values) + { + if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) + { + foreach (var loc5 in loc4.UniquesDict.First().Value) + { + loc5.IsPrimary = true; + loc4.Primarys.Add(loc5); + } + } + loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); + loc4.Columns.Sort((c1, c2) => + { + int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); + if (compare == 0) + { + bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); + bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); + compare = b2.CompareTo(b1); + } + if (compare == 0) compare = c1.Name.CompareTo(c2.Name); + return compare; + }); + loc1.Add(loc4); + } + loc1.Sort((t1, t2) => + { + var ret = t1.Schema.CompareTo(t2.Schema); + if (ret == 0) ret = t1.Name.CompareTo(t2.Name); + return ret; + }); - loc2.Clear(); - loc3.Clear(); - tables.AddRange(loc1); - } - return tables; - } + loc2.Clear(); + loc3.Clear(); + tables.AddRange(loc1); + } + return tables; + } - public List GetEnumsByDatabase(params string[] database) { - return new List(); - } - } + public List GetEnumsByDatabase(params string[] database) + { + return new List(); + } + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs index d0d6b6f4..8af8d56a 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerExpression.cs @@ -7,377 +7,429 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.SqlServer { - class SqlServerExpression : CommonExpression { +namespace FreeSql.SqlServer +{ + class SqlServerExpression : CommonExpression + { - public SqlServerExpression(CommonUtils common) : base(common) { } + public SqlServerExpression(CommonUtils common) : base(common) { } - public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.NodeType) { - case ExpressionType.Convert: - var operandExp = (exp as UnaryExpression)?.Operand; - var gentype = exp.Type.NullableTypeOrThis(); - if (gentype != operandExp.Type.NullableTypeOrThis()) { - switch (gentype.ToString()) { - case "System.Boolean": return $"(cast({getExp(operandExp)} as varchar) not in ('0','false'))"; - case "System.Byte": return $"cast({getExp(operandExp)} as tinyint)"; - case "System.Char": return $"substring(cast({getExp(operandExp)} as nvarchar),1,1)"; - case "System.DateTime": return $"cast({getExp(operandExp)} as datetime)"; - case "System.Decimal": return $"cast({getExp(operandExp)} as decimal(36,18))"; - case "System.Double": return $"cast({getExp(operandExp)} as decimal(32,16))"; - case "System.Int16": return $"cast({getExp(operandExp)} as smallint)"; - case "System.Int32": return $"cast({getExp(operandExp)} as int)"; - case "System.Int64": return $"cast({getExp(operandExp)} as bigint)"; - case "System.SByte": return $"cast({getExp(operandExp)} as tinyint)"; - case "System.Single": return $"cast({getExp(operandExp)} as decimal(14,7))"; - case "System.String": return operandExp.Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(operandExp)} as varchar(36))" : $"cast({getExp(operandExp)} as nvarchar)"; - case "System.UInt16": return $"cast({getExp(operandExp)} as smallint)"; - case "System.UInt32": return $"cast({getExp(operandExp)} as int)"; - case "System.UInt64": return $"cast({getExp(operandExp)} as bigint)"; - case "System.Guid": return $"cast({getExp(operandExp)} as uniqueidentifier)"; - } - } - break; - case ExpressionType.Call: - var callExp = exp as MethodCallExpression; + public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.NodeType) + { + case ExpressionType.Convert: + var operandExp = (exp as UnaryExpression)?.Operand; + var gentype = exp.Type.NullableTypeOrThis(); + if (gentype != operandExp.Type.NullableTypeOrThis()) + { + switch (gentype.ToString()) + { + case "System.Boolean": return $"(cast({getExp(operandExp)} as varchar) not in ('0','false'))"; + case "System.Byte": return $"cast({getExp(operandExp)} as tinyint)"; + case "System.Char": return $"substring(cast({getExp(operandExp)} as nvarchar),1,1)"; + case "System.DateTime": return $"cast({getExp(operandExp)} as datetime)"; + case "System.Decimal": return $"cast({getExp(operandExp)} as decimal(36,18))"; + case "System.Double": return $"cast({getExp(operandExp)} as decimal(32,16))"; + case "System.Int16": return $"cast({getExp(operandExp)} as smallint)"; + case "System.Int32": return $"cast({getExp(operandExp)} as int)"; + case "System.Int64": return $"cast({getExp(operandExp)} as bigint)"; + case "System.SByte": return $"cast({getExp(operandExp)} as tinyint)"; + case "System.Single": return $"cast({getExp(operandExp)} as decimal(14,7))"; + case "System.String": return operandExp.Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(operandExp)} as varchar(36))" : $"cast({getExp(operandExp)} as nvarchar)"; + case "System.UInt16": return $"cast({getExp(operandExp)} as smallint)"; + case "System.UInt32": return $"cast({getExp(operandExp)} as int)"; + case "System.UInt64": return $"cast({getExp(operandExp)} as bigint)"; + case "System.Guid": return $"cast({getExp(operandExp)} as uniqueidentifier)"; + } + } + break; + case ExpressionType.Call: + var callExp = exp as MethodCallExpression; - switch(callExp.Method.Name) { - case "Parse": - case "TryParse": - switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) { - case "System.Boolean": return $"(cast({getExp(callExp.Arguments[0])} as varchar) not in ('0','false'))"; - case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as tinyint)"; - case "System.Char": return $"substring(cast({getExp(callExp.Arguments[0])} as nvarchar),1,1)"; - case "System.DateTime": return $"cast({getExp(callExp.Arguments[0])} as datetime)"; - case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as decimal(36,18))"; - case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as decimal(32,16))"; - case "System.Int16": return $"cast({getExp(callExp.Arguments[0])} as smallint)"; - case "System.Int32": return $"cast({getExp(callExp.Arguments[0])} as int)"; - case "System.Int64": return $"cast({getExp(callExp.Arguments[0])} as bigint)"; - case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as tinyint)"; - case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as decimal(14,7))"; - case "System.UInt16": return $"cast({getExp(callExp.Arguments[0])} as smallint)"; - case "System.UInt32": return $"cast({getExp(callExp.Arguments[0])} as int)"; - case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as bigint)"; - case "System.Guid": return $"cast({getExp(callExp.Arguments[0])} as uniqueidentifier)"; - } - break; - case "NewGuid": - switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) { - case "System.Guid": return $"newid()"; - } - break; - case "Next": - if (callExp.Object?.Type == typeof(Random)) return "cast(rand()*1000000000 as int)"; - break; - case "NextDouble": - if (callExp.Object?.Type == typeof(Random)) return "rand()"; - break; - case "Random": - if (callExp.Method.DeclaringType.IsNumberType()) return "rand()"; - break; - case "ToString": - if (callExp.Object != null) return callExp.Object.Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(callExp.Object)} as varchar(36))" : $"cast({getExp(callExp.Object)} as nvarchar)"; - break; - } + switch (callExp.Method.Name) + { + case "Parse": + case "TryParse": + switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) + { + case "System.Boolean": return $"(cast({getExp(callExp.Arguments[0])} as varchar) not in ('0','false'))"; + case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as tinyint)"; + case "System.Char": return $"substring(cast({getExp(callExp.Arguments[0])} as nvarchar),1,1)"; + case "System.DateTime": return $"cast({getExp(callExp.Arguments[0])} as datetime)"; + case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as decimal(36,18))"; + case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as decimal(32,16))"; + case "System.Int16": return $"cast({getExp(callExp.Arguments[0])} as smallint)"; + case "System.Int32": return $"cast({getExp(callExp.Arguments[0])} as int)"; + case "System.Int64": return $"cast({getExp(callExp.Arguments[0])} as bigint)"; + case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as tinyint)"; + case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as decimal(14,7))"; + case "System.UInt16": return $"cast({getExp(callExp.Arguments[0])} as smallint)"; + case "System.UInt32": return $"cast({getExp(callExp.Arguments[0])} as int)"; + case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as bigint)"; + case "System.Guid": return $"cast({getExp(callExp.Arguments[0])} as uniqueidentifier)"; + } + break; + case "NewGuid": + switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) + { + case "System.Guid": return $"newid()"; + } + break; + case "Next": + if (callExp.Object?.Type == typeof(Random)) return "cast(rand()*1000000000 as int)"; + break; + case "NextDouble": + if (callExp.Object?.Type == typeof(Random)) return "rand()"; + break; + case "Random": + if (callExp.Method.DeclaringType.IsNumberType()) return "rand()"; + break; + case "ToString": + if (callExp.Object != null) return callExp.Object.Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(callExp.Object)} as varchar(36))" : $"cast({getExp(callExp.Object)} as nvarchar)"; + break; + } - var objExp = callExp.Object; - var objType = objExp?.Type; - if (objType?.FullName == "System.Byte[]") return null; + var objExp = callExp.Object; + var objType = objExp?.Type; + if (objType?.FullName == "System.Byte[]") return null; - var argIndex = 0; - if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) { - objExp = callExp.Arguments.FirstOrDefault(); - objType = objExp?.Type; - argIndex++; - } - if (objType == null) objType = callExp.Method.DeclaringType; - if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) { - var left = objExp == null ? null : getExp(objExp); - switch (callExp.Method.Name) { - case "Contains": - //判断 in - return $"({getExp(callExp.Arguments[argIndex])}) in {left}"; - } - } - break; - case ExpressionType.NewArrayInit: - var arrExp = exp as NewArrayExpression; - var arrSb = new StringBuilder(); - arrSb.Append("("); - for (var a = 0; a < arrExp.Expressions.Count; a++) { - if (a > 0) arrSb.Append(","); - arrSb.Append(getExp(arrExp.Expressions[a])); - } - if (arrSb.Length == 1) arrSb.Append("NULL"); - return arrSb.Append(")").ToString(); - case ExpressionType.ListInit: - var listExp = exp as ListInitExpression; - var listSb = new StringBuilder(); - listSb.Append("("); - for (var a = 0; a < listExp.Initializers.Count; a++) { - if (listExp.Initializers[a].Arguments.Any() == false) continue; - if (a > 0) listSb.Append(","); - listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); - } - if (listSb.Length == 1) listSb.Append("NULL"); - return listSb.Append(")").ToString(); - case ExpressionType.New: - var newExp = exp as NewExpression; - if (typeof(IList).IsAssignableFrom(newExp.Type)) { - if (newExp.Arguments.Count == 0) return "(NULL)"; - if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; - return getExp(newExp.Arguments[0]); - } - return null; - } - return null; - } + var argIndex = 0; + if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) + { + objExp = callExp.Arguments.FirstOrDefault(); + objType = objExp?.Type; + argIndex++; + } + if (objType == null) objType = callExp.Method.DeclaringType; + if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) + { + var left = objExp == null ? null : getExp(objExp); + switch (callExp.Method.Name) + { + case "Contains": + //判断 in + return $"({getExp(callExp.Arguments[argIndex])}) in {left}"; + } + } + break; + case ExpressionType.NewArrayInit: + var arrExp = exp as NewArrayExpression; + var arrSb = new StringBuilder(); + arrSb.Append("("); + for (var a = 0; a < arrExp.Expressions.Count; a++) + { + if (a > 0) arrSb.Append(","); + arrSb.Append(getExp(arrExp.Expressions[a])); + } + if (arrSb.Length == 1) arrSb.Append("NULL"); + return arrSb.Append(")").ToString(); + case ExpressionType.ListInit: + var listExp = exp as ListInitExpression; + var listSb = new StringBuilder(); + listSb.Append("("); + for (var a = 0; a < listExp.Initializers.Count; a++) + { + if (listExp.Initializers[a].Arguments.Any() == false) continue; + if (a > 0) listSb.Append(","); + listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); + } + if (listSb.Length == 1) listSb.Append("NULL"); + return listSb.Append(")").ToString(); + case ExpressionType.New: + var newExp = exp as NewExpression; + if (typeof(IList).IsAssignableFrom(newExp.Type)) + { + if (newExp.Arguments.Count == 0) return "(NULL)"; + if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; + return getExp(newExp.Arguments[0]); + } + return null; + } + return null; + } - public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Empty": return "''"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Length": return $"len({left})"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Now": return "getdate()"; - case "UtcNow": return "getutcdate()"; - case "Today": return "convert(char(10),getdate(),120)"; - case "MinValue": return "'1753/1/1 0:00:00'"; - case "MaxValue": return "'9999/12/31 23:59:59'"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Date": return $"convert(char(10),{left},120)"; - case "TimeOfDay": return $"datediff(second, convert(char(10),{left},120), {left})"; - case "DayOfWeek": return $"(datepart(weekday, {left})-1)"; - case "Day": return $"datepart(day, {left})"; - case "DayOfYear": return $"datepart(dayofyear, {left})"; - case "Month": return $"datepart(month, {left})"; - case "Year": return $"datepart(year, {left})"; - case "Hour": return $"datepart(hour, {left})"; - case "Minute": return $"datepart(minute, {left})"; - case "Second": return $"datepart(second, {left})"; - case "Millisecond": return $"(datepart(millisecond, {left})/1000)"; - case "Ticks": return $"(cast(datediff(second, '1970-1-1', {left}) as bigint)*10000000+621355968000000000)"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Zero": return "0"; - case "MinValue": return "-922337203685477580"; //微秒 Ticks / 10 - case "MaxValue": return "922337203685477580"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Days": return $"floor(({left})/{60 * 60 * 24})"; - case "Hours": return $"floor(({left})/{60 * 60}%24)"; - case "Milliseconds": return $"(cast({left} as bigint)*1000)"; - case "Minutes": return $"floor(({left})/60%60)"; - case "Seconds": return $"(({left})%60)"; - case "Ticks": return $"(cast({left} as bigint)*10000000)"; - case "TotalDays": return $"(({left})/{60 * 60 * 24})"; - case "TotalHours": return $"(({left})/{60 * 60})"; - case "TotalMilliseconds": return $"(cast({left} as bigint)*1000)"; - case "TotalMinutes": return $"(({left})/60)"; - case "TotalSeconds": return $"({left})"; - } - return null; - } + public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Empty": return "''"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Length": return $"len({left})"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Now": return "getdate()"; + case "UtcNow": return "getutcdate()"; + case "Today": return "convert(char(10),getdate(),120)"; + case "MinValue": return "'1753/1/1 0:00:00'"; + case "MaxValue": return "'9999/12/31 23:59:59'"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Date": return $"convert(char(10),{left},120)"; + case "TimeOfDay": return $"datediff(second, convert(char(10),{left},120), {left})"; + case "DayOfWeek": return $"(datepart(weekday, {left})-1)"; + case "Day": return $"datepart(day, {left})"; + case "DayOfYear": return $"datepart(dayofyear, {left})"; + case "Month": return $"datepart(month, {left})"; + case "Year": return $"datepart(year, {left})"; + case "Hour": return $"datepart(hour, {left})"; + case "Minute": return $"datepart(minute, {left})"; + case "Second": return $"datepart(second, {left})"; + case "Millisecond": return $"(datepart(millisecond, {left})/1000)"; + case "Ticks": return $"(cast(datediff(second, '1970-1-1', {left}) as bigint)*10000000+621355968000000000)"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Zero": return "0"; + case "MinValue": return "-922337203685477580"; //微秒 Ticks / 10 + case "MaxValue": return "922337203685477580"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Days": return $"floor(({left})/{60 * 60 * 24})"; + case "Hours": return $"floor(({left})/{60 * 60}%24)"; + case "Milliseconds": return $"(cast({left} as bigint)*1000)"; + case "Minutes": return $"floor(({left})/60%60)"; + case "Seconds": return $"(({left})%60)"; + case "Ticks": return $"(cast({left} as bigint)*10000000)"; + case "TotalDays": return $"(({left})/{60 * 60 * 24})"; + case "TotalHours": return $"(({left})/{60 * 60})"; + case "TotalMilliseconds": return $"(cast({left} as bigint)*1000)"; + case "TotalMinutes": return $"(({left})/60)"; + case "TotalSeconds": return $"({left})"; + } + return null; + } - public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "IsNullOrEmpty": - var arg1 = getExp(exp.Arguments[0]); - return $"({arg1} is null or {arg1} = '')"; - case "Concat": - return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), exp.Arguments.Select(a => a.Type).ToArray()); - } - } else { - var left = getExp(exp.Object); - switch (exp.Method.Name) { - case "StartsWith": - case "EndsWith": - case "Contains": - var args0Value = getExp(exp.Arguments[0]); - if (args0Value == "NULL") return $"({left}) IS NULL"; - if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(cast({args0Value} as nvarchar)+'%')")}"; - if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%'+cast({args0Value} as nvarchar))")}"; - if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; - return $"({left}) LIKE ('%'+cast({args0Value} as nvarchar)+'%')"; - case "ToLower": return $"lower({left})"; - case "ToUpper": return $"upper({left})"; - case "Substring": - var substrArgs1 = getExp(exp.Arguments[0]); - if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); - else substrArgs1 += "+1"; - if (exp.Arguments.Count == 1) return $"left({left}, {substrArgs1})"; - return $"substring({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; - case "IndexOf": - var indexOfFindStr = getExp(exp.Arguments[0]); - if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") { - var locateArgs1 = getExp(exp.Arguments[1]); - if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); - else locateArgs1 += "+1"; - return $"(charindex({left}, {indexOfFindStr}, {locateArgs1})-1)"; - } - return $"(charindex({left}, {indexOfFindStr})-1)"; - case "PadLeft": - if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})"; - return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "PadRight": - if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})"; - return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Trim": return $"ltrim(rtrim({left}))"; - case "TrimStart": return $"ltrim({left})"; - case "TrimEnd": return $"rtrim({left})"; - case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "CompareTo": return $"({left} - {getExp(exp.Arguments[0])})"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - } - } - throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.Method.Name) { - case "Abs": return $"abs({getExp(exp.Arguments[0])})"; - case "Sign": return $"sign({getExp(exp.Arguments[0])})"; - case "Floor": return $"floor({getExp(exp.Arguments[0])})"; - case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})"; - case "Round": - if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - return $"round({getExp(exp.Arguments[0])}, 0)"; - case "Exp": return $"exp({getExp(exp.Arguments[0])})"; - case "Log": return $"log({getExp(exp.Arguments[0])})"; - case "Log10": return $"log10({getExp(exp.Arguments[0])})"; - case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; - case "Cos": return $"cos({getExp(exp.Arguments[0])})"; - case "Sin": return $"sin({getExp(exp.Arguments[0])})"; - case "Tan": return $"tan({getExp(exp.Arguments[0])})"; - case "Acos": return $"acos({getExp(exp.Arguments[0])})"; - case "Asin": return $"asin({getExp(exp.Arguments[0])})"; - case "Atan": return $"atan({getExp(exp.Arguments[0])})"; - case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Truncate": return $"floor({getExp(exp.Arguments[0])})"; - } - throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"({getExp(exp.Arguments[0])} - ({getExp(exp.Arguments[1])}))"; - case "DaysInMonth": return $"datepart(day, dateadd(day, -1, dateadd(month, 1, cast({getExp(exp.Arguments[0])} as varchar) + '-' + cast({getExp(exp.Arguments[1])} as varchar) + '-1')))"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "IsNullOrEmpty": + var arg1 = getExp(exp.Arguments[0]); + return $"({arg1} is null or {arg1} = '')"; + case "Concat": + return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), exp.Arguments.Select(a => a.Type).ToArray()); + } + } + else + { + var left = getExp(exp.Object); + switch (exp.Method.Name) + { + case "StartsWith": + case "EndsWith": + case "Contains": + var args0Value = getExp(exp.Arguments[0]); + if (args0Value == "NULL") return $"({left}) IS NULL"; + if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"(cast({args0Value} as nvarchar)+'%')")}"; + if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"('%'+cast({args0Value} as nvarchar))")}"; + if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; + return $"({left}) LIKE ('%'+cast({args0Value} as nvarchar)+'%')"; + case "ToLower": return $"lower({left})"; + case "ToUpper": return $"upper({left})"; + case "Substring": + var substrArgs1 = getExp(exp.Arguments[0]); + if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); + else substrArgs1 += "+1"; + if (exp.Arguments.Count == 1) return $"left({left}, {substrArgs1})"; + return $"substring({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; + case "IndexOf": + var indexOfFindStr = getExp(exp.Arguments[0]); + if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") + { + var locateArgs1 = getExp(exp.Arguments[1]); + if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); + else locateArgs1 += "+1"; + return $"(charindex({left}, {indexOfFindStr}, {locateArgs1})-1)"; + } + return $"(charindex({left}, {indexOfFindStr})-1)"; + case "PadLeft": + if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})"; + return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "PadRight": + if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})"; + return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Trim": return $"ltrim(rtrim({left}))"; + case "TrimStart": return $"ltrim({left})"; + case "TrimEnd": return $"rtrim({left})"; + case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "CompareTo": return $"({left} - {getExp(exp.Arguments[0])})"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + } + } + throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.Method.Name) + { + case "Abs": return $"abs({getExp(exp.Arguments[0])})"; + case "Sign": return $"sign({getExp(exp.Arguments[0])})"; + case "Floor": return $"floor({getExp(exp.Arguments[0])})"; + case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})"; + case "Round": + if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + return $"round({getExp(exp.Arguments[0])}, 0)"; + case "Exp": return $"exp({getExp(exp.Arguments[0])})"; + case "Log": return $"log({getExp(exp.Arguments[0])})"; + case "Log10": return $"log10({getExp(exp.Arguments[0])})"; + case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; + case "Cos": return $"cos({getExp(exp.Arguments[0])})"; + case "Sin": return $"sin({getExp(exp.Arguments[0])})"; + case "Tan": return $"tan({getExp(exp.Arguments[0])})"; + case "Acos": return $"acos({getExp(exp.Arguments[0])})"; + case "Asin": return $"asin({getExp(exp.Arguments[0])})"; + case "Atan": return $"atan({getExp(exp.Arguments[0])})"; + case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Truncate": return $"floor({getExp(exp.Arguments[0])})"; + } + throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"({getExp(exp.Arguments[0])} - ({getExp(exp.Arguments[1])}))"; + case "DaysInMonth": return $"datepart(day, dateadd(day, -1, dateadd(month, 1, cast({getExp(exp.Arguments[0])} as varchar) + '-' + cast({getExp(exp.Arguments[1])} as varchar) + '-1')))"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "IsLeapYear": - var isLeapYearArgs1 = getExp(exp.Arguments[0]); - return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)"; + case "IsLeapYear": + var isLeapYearArgs1 = getExp(exp.Arguments[0]); + return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)"; - case "Parse": return $"cast({getExp(exp.Arguments[0])} as datetime)"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as datetime)"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"dateadd(second, {args1}, {left})"; - case "AddDays": return $"dateadd(day, {args1}, {left})"; - case "AddHours": return $"dateadd(hour, {args1}, {left})"; - case "AddMilliseconds": return $"dateadd(second, ({args1})/1000, {left})"; - case "AddMinutes": return $"dateadd(minute, {args1}, {left})"; - case "AddMonths": return $"dateadd(month, {args1}, {left})"; - case "AddSeconds": return $"dateadd(second, {args1}, {left})"; - case "AddTicks": return $"dateadd(second, ({args1})/10000000, {left})"; - case "AddYears": return $"dateadd(year, {args1}, {left})"; - case "Subtract": - switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) { - case "System.DateTime": return $"datediff(second, {args1}, {left})"; - case "System.TimeSpan": return $"dateadd(second, {args1}*-1, {left})"; - } - break; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"datediff(second,{getExp(exp.Arguments[0])},{left})"; - case "ToString": return $"convert(varchar, {left}, 121)"; - } - } - throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "FromDays": return $"(({getExp(exp.Arguments[0])})*{60 * 60 * 24})"; - case "FromHours": return $"(({getExp(exp.Arguments[0])})*{60 * 60})"; - case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})/1000)"; - case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*60)"; - case "FromSeconds": return $"({getExp(exp.Arguments[0])})"; - case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10000000)"; - case "Parse": return $"cast({getExp(exp.Arguments[0])} as bigint)"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as bigint)"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"({left}+{args1})"; - case "Subtract": return $"({left}-({args1}))"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))"; - case "ToString": return $"cast({left} as varchar)"; - } - } - throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "ToBoolean": return $"(cast({getExp(exp.Arguments[0])} as varchar) not in ('0','false'))"; - case "ToByte": return $"cast({getExp(exp.Arguments[0])} as tinyint)"; - case "ToChar": return $"substring(cast({getExp(exp.Arguments[0])} as nvarchar),1,1)"; - case "ToDateTime": return $"cast({getExp(exp.Arguments[0])} as datetime)"; - case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))"; - case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as decimal(32,16))"; - case "ToInt16": return $"cast({getExp(exp.Arguments[0])} as smallint)"; - case "ToInt32": return $"cast({getExp(exp.Arguments[0])} as int)"; - case "ToInt64": return $"cast({getExp(exp.Arguments[0])} as bigint)"; - case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as tinyint)"; - case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as decimal(14,7))"; - case "ToString": return exp.Arguments[0].Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(exp.Arguments[0])} as varchar(36))" : $"cast({getExp(exp.Arguments[0])} as nvarchar)"; - case "ToUInt16": return $"cast({getExp(exp.Arguments[0])} as smallint)"; - case "ToUInt32": return $"cast({getExp(exp.Arguments[0])} as int)"; - case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as bigint)"; - } - } - throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); - } - } + case "Parse": return $"cast({getExp(exp.Arguments[0])} as datetime)"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as datetime)"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"dateadd(second, {args1}, {left})"; + case "AddDays": return $"dateadd(day, {args1}, {left})"; + case "AddHours": return $"dateadd(hour, {args1}, {left})"; + case "AddMilliseconds": return $"dateadd(second, ({args1})/1000, {left})"; + case "AddMinutes": return $"dateadd(minute, {args1}, {left})"; + case "AddMonths": return $"dateadd(month, {args1}, {left})"; + case "AddSeconds": return $"dateadd(second, {args1}, {left})"; + case "AddTicks": return $"dateadd(second, ({args1})/10000000, {left})"; + case "AddYears": return $"dateadd(year, {args1}, {left})"; + case "Subtract": + switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) + { + case "System.DateTime": return $"datediff(second, {args1}, {left})"; + case "System.TimeSpan": return $"dateadd(second, {args1}*-1, {left})"; + } + break; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"datediff(second,{getExp(exp.Arguments[0])},{left})"; + case "ToString": return $"convert(varchar, {left}, 121)"; + } + } + throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + case "FromDays": return $"(({getExp(exp.Arguments[0])})*{60 * 60 * 24})"; + case "FromHours": return $"(({getExp(exp.Arguments[0])})*{60 * 60})"; + case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})/1000)"; + case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*60)"; + case "FromSeconds": return $"({getExp(exp.Arguments[0])})"; + case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10000000)"; + case "Parse": return $"cast({getExp(exp.Arguments[0])} as bigint)"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as bigint)"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"({left}+{args1})"; + case "Subtract": return $"({left}-({args1}))"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))"; + case "ToString": return $"cast({left} as varchar)"; + } + } + throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "ToBoolean": return $"(cast({getExp(exp.Arguments[0])} as varchar) not in ('0','false'))"; + case "ToByte": return $"cast({getExp(exp.Arguments[0])} as tinyint)"; + case "ToChar": return $"substring(cast({getExp(exp.Arguments[0])} as nvarchar),1,1)"; + case "ToDateTime": return $"cast({getExp(exp.Arguments[0])} as datetime)"; + case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))"; + case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as decimal(32,16))"; + case "ToInt16": return $"cast({getExp(exp.Arguments[0])} as smallint)"; + case "ToInt32": return $"cast({getExp(exp.Arguments[0])} as int)"; + case "ToInt64": return $"cast({getExp(exp.Arguments[0])} as bigint)"; + case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as tinyint)"; + case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as decimal(14,7))"; + case "ToString": return exp.Arguments[0].Type.NullableTypeOrThis() == typeof(Guid) ? $"cast({getExp(exp.Arguments[0])} as varchar(36))" : $"cast({getExp(exp.Arguments[0])} as nvarchar)"; + case "ToUInt16": return $"cast({getExp(exp.Arguments[0])} as smallint)"; + case "ToUInt32": return $"cast({getExp(exp.Arguments[0])} as int)"; + case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as bigint)"; + } + } + throw new Exception($"SqlServerExpression 未实现函数表达式 {exp} 解析"); + } + } } diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerExtensions.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerExtensions.cs index c9fe63b4..e7d5dd5f 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerExtensions.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerExtensions.cs @@ -1,11 +1,12 @@ -public static partial class FreeSqlGlobalExtensions { +public static partial class FreeSqlGlobalExtensions +{ - /// - /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 - /// - /// - /// - /// - public static string FormatSqlServer(this string that, params object[] args) => _sqlserverAdo.Addslashes(that, args); - static FreeSql.SqlServer.SqlServerAdo _sqlserverAdo = new FreeSql.SqlServer.SqlServerAdo(); + /// + /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 + /// + /// + /// + /// + public static string FormatSqlServer(this string that, params object[] args) => _sqlserverAdo.Addslashes(that, args); + static FreeSql.SqlServer.SqlServerAdo _sqlserverAdo = new FreeSql.SqlServer.SqlServerAdo(); } diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerProvider.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerProvider.cs index f6abcc0d..f0e2fe85 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerProvider.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerProvider.cs @@ -4,58 +4,67 @@ using FreeSql.SqlServer.Curd; using System; using System.Collections.Generic; -namespace FreeSql.SqlServer { +namespace FreeSql.SqlServer +{ - public class SqlServerProvider : IFreeSql { + public class SqlServerProvider : IFreeSql + { - public ISelect Select() where T1 : class => new SqlServerSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public ISelect Select(object dywhere) where T1 : class => new SqlServerSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IInsert Insert() where T1 : class => new SqlServerInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); - public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); - public IUpdate Update() where T1 : class => new SqlServerUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IUpdate Update(object dywhere) where T1 : class => new SqlServerUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IDelete Delete() where T1 : class => new SqlServerDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IDelete Delete(object dywhere) where T1 : class => new SqlServerDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public ISelect Select() where T1 : class => new SqlServerSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public ISelect Select(object dywhere) where T1 : class => new SqlServerSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IInsert Insert() where T1 : class => new SqlServerInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); + public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); + public IUpdate Update() where T1 : class => new SqlServerUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IUpdate Update(object dywhere) where T1 : class => new SqlServerUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IDelete Delete() where T1 : class => new SqlServerDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IDelete Delete(object dywhere) where T1 : class => new SqlServerDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IAdo Ado { get; } - public IAop Aop { get; } - public ICodeFirst CodeFirst { get; } - public IDbFirst DbFirst { get; } - public SqlServerProvider(string masterConnectionString, string[] slaveConnectionString) { - this.InternalCommonUtils = new SqlServerUtils(this); - this.InternalCommonExpression = new SqlServerExpression(this.InternalCommonUtils); + public IAdo Ado { get; } + public IAop Aop { get; } + public ICodeFirst CodeFirst { get; } + public IDbFirst DbFirst { get; } + public SqlServerProvider(string masterConnectionString, string[] slaveConnectionString) + { + this.InternalCommonUtils = new SqlServerUtils(this); + this.InternalCommonExpression = new SqlServerExpression(this.InternalCommonUtils); - this.Ado = new SqlServerAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); - this.Aop = new AopProvider(); + this.Ado = new SqlServerAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); + this.Aop = new AopProvider(); - this.DbFirst = new SqlServerDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - this.CodeFirst = new SqlServerCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + this.DbFirst = new SqlServerDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + this.CodeFirst = new SqlServerCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - if (this.Ado.MasterPool != null) - using (var conn = this.Ado.MasterPool.Get()) { - try { - (this.InternalCommonUtils as SqlServerUtils).IsSelectRowNumber = int.Parse(conn.Value.ServerVersion.Split('.')[0]) <= 10; - } catch { - } - } - } + if (this.Ado.MasterPool != null) + using (var conn = this.Ado.MasterPool.Get()) + { + try + { + (this.InternalCommonUtils as SqlServerUtils).IsSelectRowNumber = int.Parse(conn.Value.ServerVersion.Split('.')[0]) <= 10; + } + catch + { + } + } + } - internal CommonUtils InternalCommonUtils { get; } - internal CommonExpression InternalCommonExpression { get; } + internal CommonUtils InternalCommonUtils { get; } + internal CommonExpression InternalCommonExpression { get; } - public void Transaction(Action handler) => Ado.Transaction(handler); + public void Transaction(Action handler) => Ado.Transaction(handler); - public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); + public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); - ~SqlServerProvider() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - (this.Ado as AdoProvider)?.Dispose(); - } - } + ~SqlServerProvider() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + (this.Ado as AdoProvider)?.Dispose(); + } + } } diff --git a/Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs b/Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs index 5c0812e6..5bef8a09 100644 --- a/Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs +++ b/Providers/FreeSql.Provider.SqlServer/SqlServerUtils.cs @@ -8,75 +8,88 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.SqlServer { +namespace FreeSql.SqlServer +{ - class SqlServerUtils : CommonUtils { - public SqlServerUtils(IFreeSql orm) : base(orm) { - } + class SqlServerUtils : CommonUtils + { + public SqlServerUtils(IFreeSql orm) : base(orm) + { + } - public bool IsSelectRowNumber = true; + public bool IsSelectRowNumber = true; - public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) { - if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; - if (value?.Equals(DateTime.MinValue) == true) value = new DateTime(1970, 1, 1); - var ret = new SqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; - var tp = _orm.CodeFirst.GetDbInfo(type)?.type; - if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value; - _params?.Add(ret); - return ret; - } + public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) + { + if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; + if (value?.Equals(DateTime.MinValue) == true) value = new DateTime(1970, 1, 1); + var ret = new SqlParameter { ParameterName = QuoteParamterName(parameterName), Value = value }; + var tp = _orm.CodeFirst.GetDbInfo(type)?.type; + if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value; + _params?.Add(ret); + return ret; + } - public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => - Utils.GetDbParamtersByObject(sql, obj, "@", (name, type, value) => { - if (value?.Equals(DateTime.MinValue) == true) value = new DateTime(1970, 1, 1); - var ret = new SqlParameter { ParameterName = $"@{name}", Value = value }; - var tp = _orm.CodeFirst.GetDbInfo(type)?.type; - if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value; - return ret; - }); + public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => + Utils.GetDbParamtersByObject(sql, obj, "@", (name, type, value) => + { + if (value?.Equals(DateTime.MinValue) == true) value = new DateTime(1970, 1, 1); + var ret = new SqlParameter { ParameterName = $"@{name}", Value = value }; + var tp = _orm.CodeFirst.GetDbInfo(type)?.type; + if (tp != null) ret.SqlDbType = (SqlDbType)tp.Value; + return ret; + }); - public override string FormatSql(string sql, params object[] args) => sql?.FormatSqlServer(args); - public override string QuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"[{nametrim.TrimStart('[').TrimEnd(']').Replace(".", "].[")}]"; - } - public override string TrimQuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"{nametrim.TrimStart('[').TrimEnd(']').Replace("].[", ".").Replace(".[", ".")}"; - } - public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; - public override string IsNull(string sql, object value) => $"isnull({sql}, {value})"; - public override string StringConcat(string[] objs, Type[] types) { - var sb = new StringBuilder(); - var news = new string[objs.Length]; - for (var a = 0; a < objs.Length; a++) - news[a] = types[a] == typeof(string) ? objs[a] : $"cast({objs[a]} as nvarchar)"; - return string.Join(" + ", news); - } - public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; + public override string FormatSql(string sql, params object[] args) => sql?.FormatSqlServer(args); + public override string QuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"[{nametrim.TrimStart('[').TrimEnd(']').Replace(".", "].[")}]"; + } + public override string TrimQuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"{nametrim.TrimStart('[').TrimEnd(']').Replace("].[", ".").Replace(".[", ".")}"; + } + public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; + public override string IsNull(string sql, object value) => $"isnull({sql}, {value})"; + public override string StringConcat(string[] objs, Type[] types) + { + var sb = new StringBuilder(); + var news = new string[objs.Length]; + for (var a = 0; a < objs.Length; a++) + news[a] = types[a] == typeof(string) ? objs[a] : $"cast({objs[a]} as nvarchar)"; + return string.Join(" + ", news); + } + public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; - public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; - public override string QuoteReadColumn(Type type, string columnName) => columnName; + public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; + public override string QuoteReadColumn(Type type, string columnName) => columnName; - public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) { - if (value == null) return "NULL"; - if (type == typeof(byte[])) { - var bytes = value as byte[]; - var sb = new StringBuilder().Append("0x"); - foreach (var vc in bytes) { - if (vc < 10) sb.Append("0"); - sb.Append(vc.ToString("X")); - } - return sb.ToString(); - } else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) { - var ts = (TimeSpan)value; - value = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}.{ts.Milliseconds}"; - } - return FormatSql("{0}", value, 1); - } - } + public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) + { + if (value == null) return "NULL"; + if (type == typeof(byte[])) + { + var bytes = value as byte[]; + var sb = new StringBuilder().Append("0x"); + foreach (var vc in bytes) + { + if (vc < 10) sb.Append("0"); + sb.Append(vc.ToString("X")); + } + return sb.ToString(); + } + else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) + { + var ts = (TimeSpan)value; + value = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}.{ts.Milliseconds}"; + } + return FormatSql("{0}", value, 1); + } + } } diff --git a/Providers/FreeSql.Provider.Sqlite/Curd/SqliteDelete.cs b/Providers/FreeSql.Provider.Sqlite/Curd/SqliteDelete.cs index 13f60c51..f582cb6b 100644 --- a/Providers/FreeSql.Provider.Sqlite/Curd/SqliteDelete.cs +++ b/Providers/FreeSql.Provider.Sqlite/Curd/SqliteDelete.cs @@ -5,18 +5,23 @@ using System.Data; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Sqlite.Curd { +namespace FreeSql.Sqlite.Curd +{ - class SqliteDelete : Internal.CommonProvider.DeleteProvider where T1 : class { - public SqliteDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + class SqliteDelete : Internal.CommonProvider.DeleteProvider where T1 : class + { + public SqliteDelete(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override List ExecuteDeleted() { - throw new NotImplementedException(); - } - public override Task> ExecuteDeletedAsync() { - throw new NotImplementedException(); - } - } + public override List ExecuteDeleted() + { + throw new NotImplementedException(); + } + public override Task> ExecuteDeletedAsync() + { + throw new NotImplementedException(); + } + } } diff --git a/Providers/FreeSql.Provider.Sqlite/Curd/SqliteInsert.cs b/Providers/FreeSql.Provider.Sqlite/Curd/SqliteInsert.cs index 80ec45dc..ab43f919 100644 --- a/Providers/FreeSql.Provider.Sqlite/Curd/SqliteInsert.cs +++ b/Providers/FreeSql.Provider.Sqlite/Curd/SqliteInsert.cs @@ -6,76 +6,93 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Sqlite.Curd { +namespace FreeSql.Sqlite.Curd +{ - class SqliteInsert : Internal.CommonProvider.InsertProvider where T1 : class { - public SqliteInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) - : base(orm, commonUtils, commonExpression) { - } + class SqliteInsert : Internal.CommonProvider.InsertProvider where T1 : class + { + public SqliteInsert(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) + : base(orm, commonUtils, commonExpression) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(5000, 999); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(5000, 999); - public override long ExecuteIdentity() => base.SplitExecuteIdentity(5000, 999); - public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(5000, 999); - public override List ExecuteInserted() => base.SplitExecuteInserted(5000, 999); - public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(5000, 999); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(5000, 999); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(5000, 999); + public override long ExecuteIdentity() => base.SplitExecuteIdentity(5000, 999); + public override Task ExecuteIdentityAsync() => base.SplitExecuteIdentityAsync(5000, 999); + public override List ExecuteInserted() => base.SplitExecuteInserted(5000, 999); + public override Task> ExecuteInsertedAsync() => base.SplitExecuteInsertedAsync(5000, 999); - protected override long RawExecuteIdentity() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + protected override long RawExecuteIdentity() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - sql = string.Concat(sql, "; SELECT last_insert_rowid();"); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - long ret = 0; - Exception exception = null; - try { - long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out ret); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - async protected override Task RawExecuteIdentityAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return 0; + sql = string.Concat(sql, "; SELECT last_insert_rowid();"); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + long ret = 0; + Exception exception = null; + try + { + long.TryParse(string.Concat(_orm.Ado.ExecuteScalar(_connection, _transaction, CommandType.Text, sql, _params)), out ret); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + async protected override Task RawExecuteIdentityAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return 0; - sql = string.Concat(sql, "; SELECT last_insert_rowid();"); - var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); - _orm.Aop.CurdBefore?.Invoke(this, before); - long ret = 0; - Exception exception = null; - try { - long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out ret); - } catch (Exception ex) { - exception = ex; - throw ex; - } finally { - var after = new Aop.CurdAfterEventArgs(before, exception, ret); - _orm.Aop.CurdAfter?.Invoke(this, after); - } - this.ClearData(); - return ret; - } - protected override List RawExecuteInserted() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + sql = string.Concat(sql, "; SELECT last_insert_rowid();"); + var before = new Aop.CurdBeforeEventArgs(_table.Type, Aop.CurdType.Insert, sql, _params); + _orm.Aop.CurdBefore?.Invoke(this, before); + long ret = 0; + Exception exception = null; + try + { + long.TryParse(string.Concat(await _orm.Ado.ExecuteScalarAsync(_connection, _transaction, CommandType.Text, sql, _params)), out ret); + } + catch (Exception ex) + { + exception = ex; + throw ex; + } + finally + { + var after = new Aop.CurdAfterEventArgs(before, exception, ret); + _orm.Aop.CurdAfter?.Invoke(this, after); + } + this.ClearData(); + return ret; + } + protected override List RawExecuteInserted() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - this.RawExecuteAffrows(); - return _source; - } - async protected override Task> RawExecuteInsertedAsync() { - var sql = this.ToSql(); - if (string.IsNullOrEmpty(sql)) return new List(); + this.RawExecuteAffrows(); + return _source; + } + async protected override Task> RawExecuteInsertedAsync() + { + var sql = this.ToSql(); + if (string.IsNullOrEmpty(sql)) return new List(); - await this.RawExecuteAffrowsAsync(); - return _source; - } - } + await this.RawExecuteAffrowsAsync(); + return _source; + } + } } diff --git a/Providers/FreeSql.Provider.Sqlite/Curd/SqliteSelect.cs b/Providers/FreeSql.Provider.Sqlite/Curd/SqliteSelect.cs index d7dd6253..e21a1b36 100644 --- a/Providers/FreeSql.Provider.Sqlite/Curd/SqliteSelect.cs +++ b/Providers/FreeSql.Provider.Sqlite/Curd/SqliteSelect.cs @@ -6,123 +6,145 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.Sqlite.Curd { +namespace FreeSql.Sqlite.Curd +{ - class SqliteSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class { + class SqliteSelect : FreeSql.Internal.CommonProvider.Select1Provider where T1 : class + { - internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) { - if (_orm.CodeFirst.IsAutoSyncStructure) - _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); + internal static string ToSqlStatic(CommonUtils _commonUtils, string _select, bool _distinct, string field, StringBuilder _join, StringBuilder _where, string _groupby, string _having, string _orderby, int _skip, int _limit, List _tables, Func tableRuleInvoke, IFreeSql _orm) + { + if (_orm.CodeFirst.IsAutoSyncStructure) + _orm.CodeFirst.SyncStructure(_tables.Select(a => a.Table.Type).ToArray()); - var sb = new StringBuilder(); - var sbnav = new StringBuilder(); - sb.Append(_select); - if (_distinct) sb.Append("DISTINCT "); - sb.Append(field).Append(" \r\nFROM "); - var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); - var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); - for (var a = 0; a < tbsfrom.Length; a++) { - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); - if (tbsjoin.Length > 0) { - //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 - for (var b = 1; b < tbsfrom.Length; b++) { - sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); - if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); - else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); - } - break; - } else { - if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); - if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); - } - if (a < tbsfrom.Length - 1) sb.Append(", "); - } - foreach (var tb in tbsjoin) { - if (tb.Type == SelectTableInfoType.Parent) continue; - switch (tb.Type) { - case SelectTableInfoType.LeftJoin: - sb.Append(" \r\nLEFT JOIN "); - break; - case SelectTableInfoType.InnerJoin: - sb.Append(" \r\nINNER JOIN "); - break; - case SelectTableInfoType.RightJoin: - sb.Append(" \r\nRIGHT JOIN "); - break; - } - sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); - if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); - } - if (_join.Length > 0) sb.Append(_join); + var sb = new StringBuilder(); + var sbnav = new StringBuilder(); + sb.Append(_select); + if (_distinct) sb.Append("DISTINCT "); + sb.Append(field).Append(" \r\nFROM "); + var tbsjoin = _tables.Where(a => a.Type != SelectTableInfoType.From).ToArray(); + var tbsfrom = _tables.Where(a => a.Type == SelectTableInfoType.From).ToArray(); + for (var a = 0; a < tbsfrom.Length; a++) + { + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[a].Table.Type, tbsfrom[a].Table.DbName))).Append(" ").Append(tbsfrom[a].Alias); + if (tbsjoin.Length > 0) + { + //如果存在 join 查询,则处理 from t1, t2 改为 from t1 inner join t2 on 1 = 1 + for (var b = 1; b < tbsfrom.Length; b++) + { + sb.Append(" \r\nLEFT JOIN ").Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tbsfrom[b].Table.Type, tbsfrom[b].Table.DbName))).Append(" ").Append(tbsfrom[b].Alias); + if (string.IsNullOrEmpty(tbsfrom[b].NavigateCondition) && string.IsNullOrEmpty(tbsfrom[b].On)) sb.Append(" ON 1 = 1"); + else sb.Append(" ON ").Append(tbsfrom[b].NavigateCondition ?? tbsfrom[b].On); + } + break; + } + else + { + if (!string.IsNullOrEmpty(tbsfrom[a].NavigateCondition)) sbnav.Append(" AND (").Append(tbsfrom[a].NavigateCondition).Append(")"); + if (!string.IsNullOrEmpty(tbsfrom[a].On)) sbnav.Append(" AND (").Append(tbsfrom[a].On).Append(")"); + } + if (a < tbsfrom.Length - 1) sb.Append(", "); + } + foreach (var tb in tbsjoin) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + switch (tb.Type) + { + case SelectTableInfoType.LeftJoin: + sb.Append(" \r\nLEFT JOIN "); + break; + case SelectTableInfoType.InnerJoin: + sb.Append(" \r\nINNER JOIN "); + break; + case SelectTableInfoType.RightJoin: + sb.Append(" \r\nRIGHT JOIN "); + break; + } + sb.Append(_commonUtils.QuoteSqlName(tableRuleInvoke(tb.Table.Type, tb.Table.DbName))).Append(" ").Append(tb.Alias).Append(" ON ").Append(tb.On ?? tb.NavigateCondition); + if (!string.IsNullOrEmpty(tb.On) && !string.IsNullOrEmpty(tb.NavigateCondition)) sbnav.Append(" AND (").Append(tb.NavigateCondition).Append(")"); + } + if (_join.Length > 0) sb.Append(_join); - sbnav.Append(_where); - foreach (var tb in _tables) { - if (tb.Type == SelectTableInfoType.Parent) continue; - if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) - sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); - } - if (sbnav.Length > 0) { - sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); - } - if (string.IsNullOrEmpty(_groupby) == false) { - sb.Append(_groupby); - if (string.IsNullOrEmpty(_having) == false) - sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); - } - sb.Append(_orderby); - if (_skip > 0 || _limit > 0) - sb.Append(" \r\nlimit ").Append(Math.Max(0, _skip)).Append(",").Append(_limit > 0 ? _limit : -1); + sbnav.Append(_where); + foreach (var tb in _tables) + { + if (tb.Type == SelectTableInfoType.Parent) continue; + if (string.IsNullOrEmpty(tb.Table.SelectFilter) == false) + sbnav.Append(" AND (").Append(tb.Table.SelectFilter.Replace("a.", $"{tb.Alias}.")).Append(")"); + } + if (sbnav.Length > 0) + { + sb.Append(" \r\nWHERE ").Append(sbnav.Remove(0, 5)); + } + if (string.IsNullOrEmpty(_groupby) == false) + { + sb.Append(_groupby); + if (string.IsNullOrEmpty(_having) == false) + sb.Append(" \r\nHAVING ").Append(_having.Substring(5)); + } + sb.Append(_orderby); + if (_skip > 0 || _limit > 0) + sb.Append(" \r\nlimit ").Append(Math.Max(0, _skip)).Append(",").Append(_limit > 0 ? _limit : -1); - sbnav.Clear(); - return sb.ToString(); - } + sbnav.Clear(); + return sb.ToString(); + } - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } - public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } - class SqliteSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class { - public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } - public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); - } + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override ISelect From(Expression, T2, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override ISelect From(Expression, T2, T3, T4, T5, T6, T7, T8, T9, T10, ISelectFromExpression>> exp) { this.InternalFrom(exp?.Body); var ret = new SqliteSelect(_orm, _commonUtils, _commonExpression, null); SqliteSelect.CopyData(this, ret, exp?.Parameters); return ret; } + public override string ToSql(string field = null) => ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select2Provider where T1 : class where T2 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select3Provider where T1 : class where T2 : class where T3 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select4Provider where T1 : class where T2 : class where T3 : class where T4 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select5Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select6Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select7Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select8Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select9Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } + class SqliteSelect : FreeSql.Internal.CommonProvider.Select10Provider where T1 : class where T2 : class where T3 : class where T4 : class where T5 : class where T6 : class where T7 : class where T8 : class where T9 : class where T10 : class + { + public SqliteSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { } + public override string ToSql(string field = null) => SqliteSelect.ToSqlStatic(_commonUtils, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, TableRuleInvoke, _orm); + } } diff --git a/Providers/FreeSql.Provider.Sqlite/Curd/SqliteUpdate.cs b/Providers/FreeSql.Provider.Sqlite/Curd/SqliteUpdate.cs index 0915c757..a7a568a4 100644 --- a/Providers/FreeSql.Provider.Sqlite/Curd/SqliteUpdate.cs +++ b/Providers/FreeSql.Provider.Sqlite/Curd/SqliteUpdate.cs @@ -7,55 +7,66 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace FreeSql.Sqlite.Curd { +namespace FreeSql.Sqlite.Curd +{ - class SqliteUpdate : Internal.CommonProvider.UpdateProvider where T1 : class { + class SqliteUpdate : Internal.CommonProvider.UpdateProvider where T1 : class + { - public SqliteUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) - : base(orm, commonUtils, commonExpression, dywhere) { - } + public SqliteUpdate(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) + : base(orm, commonUtils, commonExpression, dywhere) + { + } - public override int ExecuteAffrows() => base.SplitExecuteAffrows(200, 999); - public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(200, 999); - public override List ExecuteUpdated() => base.SplitExecuteUpdated(200, 999); - public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(200, 999); + public override int ExecuteAffrows() => base.SplitExecuteAffrows(200, 999); + public override Task ExecuteAffrowsAsync() => base.SplitExecuteAffrowsAsync(200, 999); + public override List ExecuteUpdated() => base.SplitExecuteUpdated(200, 999); + public override Task> ExecuteUpdatedAsync() => base.SplitExecuteUpdatedAsync(200, 999); - protected override List RawExecuteUpdated() { - throw new NotImplementedException(); - } - protected override Task> RawExecuteUpdatedAsync() { - throw new NotImplementedException(); - } + protected override List RawExecuteUpdated() + { + throw new NotImplementedException(); + } + protected override Task> RawExecuteUpdatedAsync() + { + throw new NotImplementedException(); + } - protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) { - if (_table.Primarys.Length == 1) { - caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); - return; - } - caseWhen.Append("CONCAT("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) caseWhen.Append(", "); - caseWhen.Append(_commonUtils.QuoteReadColumn(pk.Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))); - ++pkidx; - } - caseWhen.Append(")"); - } + protected override void ToSqlCase(StringBuilder caseWhen, ColumnInfo[] primarys) + { + if (_table.Primarys.Length == 1) + { + caseWhen.Append(_commonUtils.QuoteReadColumn(_table.Primarys.First().Attribute.MapType, _commonUtils.QuoteSqlName(_table.Primarys.First().Attribute.Name))); + return; + } + caseWhen.Append("CONCAT("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) caseWhen.Append(", "); + caseWhen.Append(_commonUtils.QuoteReadColumn(pk.Attribute.MapType, _commonUtils.QuoteSqlName(pk.Attribute.Name))); + ++pkidx; + } + caseWhen.Append(")"); + } - protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) { - if (_table.Primarys.Length == 1) { - sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); - return; - } - sb.Append("CONCAT("); - var pkidx = 0; - foreach (var pk in _table.Primarys) { - if (pkidx > 0) sb.Append(", "); - sb.Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))); - ++pkidx; - } - sb.Append(")"); - } - } + protected override void ToSqlWhen(StringBuilder sb, ColumnInfo[] primarys, object d) + { + if (_table.Primarys.Length == 1) + { + sb.Append(_commonUtils.FormatSql("{0}", _table.Primarys.First().GetMapValue(d))); + return; + } + sb.Append("CONCAT("); + var pkidx = 0; + foreach (var pk in _table.Primarys) + { + if (pkidx > 0) sb.Append(", "); + sb.Append(_commonUtils.FormatSql("{0}", pk.GetMapValue(d))); + ++pkidx; + } + sb.Append(")"); + } + } } diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteAdo/SqliteAdo.cs b/Providers/FreeSql.Provider.Sqlite/SqliteAdo/SqliteAdo.cs index 1bc44c5f..137dd99e 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteAdo/SqliteAdo.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteAdo/SqliteAdo.cs @@ -7,54 +7,63 @@ using System.Data.SQLite; using System.Text; using System.Threading; -namespace FreeSql.Sqlite { - class SqliteAdo : FreeSql.Internal.CommonProvider.AdoProvider { - public SqliteAdo() : base(DataType.Sqlite) { } - public SqliteAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.Sqlite) { - base._util = util; - if (!string.IsNullOrEmpty(masterConnectionString)) - MasterPool = new SqliteConnectionPool("主库", masterConnectionString, null, null); - if (slaveConnectionStrings != null) { - foreach (var slaveConnectionString in slaveConnectionStrings) { - var slavePool = new SqliteConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); - SlavePools.Add(slavePool); - } - } - } - static DateTime dt1970 = new DateTime(1970, 1, 1); - public override object AddslashesProcessParam(object param, Type mapType) { - if (param == null) return "NULL"; - if (mapType != null && mapType != param.GetType()) - param = Utils.GetDataReaderValue(mapType, param); - if (param is bool || param is bool?) - return (bool)param ? 1 : 0; - else if (param is string || param is char) - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - else if (param is Enum) - return ((Enum)param).ToInt64(); - else if (decimal.TryParse(string.Concat(param), out var trydec)) - return param; - else if (param is DateTime || param is DateTime?) - return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss"), "'"); - else if (param is TimeSpan || param is TimeSpan?) - return ((TimeSpan)param).Ticks / 10000; - else if (param is IEnumerable) { - var sb = new StringBuilder(); - var ie = param as IEnumerable; - foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); - return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); - } - return string.Concat("'", param.ToString().Replace("'", "''"), "'"); - } +namespace FreeSql.Sqlite +{ + class SqliteAdo : FreeSql.Internal.CommonProvider.AdoProvider + { + public SqliteAdo() : base(DataType.Sqlite) { } + public SqliteAdo(CommonUtils util, string masterConnectionString, string[] slaveConnectionStrings) : base(DataType.Sqlite) + { + base._util = util; + if (!string.IsNullOrEmpty(masterConnectionString)) + MasterPool = new SqliteConnectionPool("主库", masterConnectionString, null, null); + if (slaveConnectionStrings != null) + { + foreach (var slaveConnectionString in slaveConnectionStrings) + { + var slavePool = new SqliteConnectionPool($"从库{SlavePools.Count + 1}", slaveConnectionString, () => Interlocked.Decrement(ref slaveUnavailables), () => Interlocked.Increment(ref slaveUnavailables)); + SlavePools.Add(slavePool); + } + } + } + static DateTime dt1970 = new DateTime(1970, 1, 1); + public override object AddslashesProcessParam(object param, Type mapType) + { + if (param == null) return "NULL"; + if (mapType != null && mapType != param.GetType()) + param = Utils.GetDataReaderValue(mapType, param); + if (param is bool || param is bool?) + return (bool)param ? 1 : 0; + else if (param is string || param is char) + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + else if (param is Enum) + return ((Enum)param).ToInt64(); + else if (decimal.TryParse(string.Concat(param), out var trydec)) + return param; + else if (param is DateTime || param is DateTime?) + return string.Concat("'", ((DateTime)param).ToString("yyyy-MM-dd HH:mm:ss"), "'"); + else if (param is TimeSpan || param is TimeSpan?) + return ((TimeSpan)param).Ticks / 10000; + else if (param is IEnumerable) + { + var sb = new StringBuilder(); + var ie = param as IEnumerable; + foreach (var z in ie) sb.Append(",").Append(AddslashesProcessParam(z, mapType)); + return sb.Length == 0 ? "(NULL)" : sb.Remove(0, 1).Insert(0, "(").Append(")").ToString(); + } + return string.Concat("'", param.ToString().Replace("'", "''"), "'"); + } - protected override DbCommand CreateCommand() { - return new SQLiteCommand(); - } + protected override DbCommand CreateCommand() + { + return new SQLiteCommand(); + } - protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) { - (pool as SqliteConnectionPool).Return(conn, ex); - } + protected override void ReturnConnection(ObjectPool pool, Object conn, Exception ex) + { + (pool as SqliteConnectionPool).Return(conn, ex); + } - protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); - } + protected override DbParameter[] GetDbParamtersByObject(string sql, object obj) => _util.GetDbParamtersByObject(sql, obj); + } } diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteAdo/SqliteConnectionPool.cs b/Providers/FreeSql.Provider.Sqlite/SqliteAdo/SqliteConnectionPool.cs index c65580f7..8cad9db5 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteAdo/SqliteConnectionPool.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteAdo/SqliteConnectionPool.cs @@ -10,205 +10,250 @@ using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; -namespace FreeSql.Sqlite { +namespace FreeSql.Sqlite +{ - class SqliteConnectionPool : ObjectPool { + class SqliteConnectionPool : ObjectPool + { - internal Action availableHandler; - internal Action unavailableHandler; + internal Action availableHandler; + internal Action unavailableHandler; - public SqliteConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) { - policy = new SqliteConnectionPoolPolicy { - _pool = this, - Name = name - }; - this.Policy = policy; - policy.ConnectionString = connectionString; + public SqliteConnectionPool(string name, string connectionString, Action availableHandler, Action unavailableHandler) : base(null) + { + policy = new SqliteConnectionPoolPolicy + { + _pool = this, + Name = name + }; + this.Policy = policy; + policy.ConnectionString = connectionString; - this.availableHandler = availableHandler; - this.unavailableHandler = unavailableHandler; - } + this.availableHandler = availableHandler; + this.unavailableHandler = unavailableHandler; + } - public void Return(Object obj, Exception exception, bool isRecreate = false) { - if (exception != null && exception is SQLiteException) { - try { if (obj.Value.Ping() == false) obj.Value.OpenAndAttach(policy.Attaches); } catch { base.SetUnavailable(exception); } - } - base.Return(obj, isRecreate); - } + public void Return(Object obj, Exception exception, bool isRecreate = false) + { + if (exception != null && exception is SQLiteException) + { + try { if (obj.Value.Ping() == false) obj.Value.OpenAndAttach(policy.Attaches); } catch { base.SetUnavailable(exception); } + } + base.Return(obj, isRecreate); + } - internal SqliteConnectionPoolPolicy policy; - } + internal SqliteConnectionPoolPolicy policy; + } - class SqliteConnectionPoolPolicy : IPolicy { + class SqliteConnectionPoolPolicy : IPolicy + { - internal SqliteConnectionPool _pool; - public string Name { get; set; } = "Sqlite SQLiteConnection 对象池"; - public int PoolSize { get; set; } = 100; - public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); - public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; - public int AsyncGetCapacity { get; set; } = 10000; - public bool IsThrowGetTimeoutException { get; set; } = true; - public int CheckAvailableInterval { get; set; } = 5; - public string[] Attaches = new string[0]; + internal SqliteConnectionPool _pool; + public string Name { get; set; } = "Sqlite SQLiteConnection 对象池"; + public int PoolSize { get; set; } = 100; + public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10); + public TimeSpan IdleTimeout { get; set; } = TimeSpan.Zero; + public int AsyncGetCapacity { get; set; } = 10000; + public bool IsThrowGetTimeoutException { get; set; } = true; + public int CheckAvailableInterval { get; set; } = 5; + public string[] Attaches = new string[0]; - static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - private string _connectionString; - public string ConnectionString { - get => _connectionString; - set { - _connectionString = value ?? ""; + static ConcurrentDictionary dicConnStrIncr = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + private string _connectionString; + public string ConnectionString + { + get => _connectionString; + set + { + _connectionString = value ?? ""; - var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)"; - Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100; - var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); - PoolSize = poolsize + connStrIncr; - _connectionString = m.Success ? - Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) : - $"{_connectionString};Max pool size={PoolSize}"; + var pattern = @"Max\s*pool\s*size\s*=\s*(\d+)"; + Match m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success == false || int.TryParse(m.Groups[1].Value, out var poolsize) == false || poolsize <= 0) poolsize = 100; + var connStrIncr = dicConnStrIncr.AddOrUpdate(_connectionString, 1, (oldkey, oldval) => oldval + 1); + PoolSize = poolsize + connStrIncr; + _connectionString = m.Success ? + Regex.Replace(_connectionString, pattern, $"Max pool size={PoolSize}", RegexOptions.IgnoreCase) : + $"{_connectionString};Max pool size={PoolSize}"; - pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + pattern = @"Connection\s*LifeTime\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + IdleTimeout = TimeSpan.FromSeconds(int.Parse(m.Groups[1].Value)); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - var minPoolSize = 0; - pattern = @"Min\s*pool\s*size\s*=\s*(\d+)"; - m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); - if (m.Success) { - minPoolSize = int.Parse(m.Groups[1].Value); - _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); - } + var minPoolSize = 0; + pattern = @"Min\s*pool\s*size\s*=\s*(\d+)"; + m = Regex.Match(_connectionString, pattern, RegexOptions.IgnoreCase); + if (m.Success) + { + minPoolSize = int.Parse(m.Groups[1].Value); + _connectionString = Regex.Replace(_connectionString, pattern, "", RegexOptions.IgnoreCase); + } - var att = Regex.Split(_connectionString, @"Attachs\s*=\s*", RegexOptions.IgnoreCase); - if (att.Length == 2) { - var idx = att[1].IndexOf(';'); - Attaches = (idx == -1 ? att[1] : att[1].Substring(0, idx)).Split(','); - } + var att = Regex.Split(_connectionString, @"Attachs\s*=\s*", RegexOptions.IgnoreCase); + if (att.Length == 2) + { + var idx = att[1].IndexOf(';'); + Attaches = (idx == -1 ? att[1] : att[1].Substring(0, idx)).Split(','); + } - FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); - } - } + FreeSql.Internal.CommonUtils.PrevReheatConnectionPool(_pool, minPoolSize); + } + } - public bool OnCheckAvailable(Object obj) { - if (obj.Value.State == ConnectionState.Closed) obj.Value.OpenAndAttach(Attaches); - return obj.Value.Ping(true); - } + public bool OnCheckAvailable(Object obj) + { + if (obj.Value.State == ConnectionState.Closed) obj.Value.OpenAndAttach(Attaches); + return obj.Value.Ping(true); + } - public DbConnection OnCreate() { - var conn = new SQLiteConnection(_connectionString); - return conn; - } + public DbConnection OnCreate() + { + var conn = new SQLiteConnection(_connectionString); + return conn; + } - public void OnDestroy(DbConnection obj) { - if (obj.State != ConnectionState.Closed) obj.Close(); - obj.Dispose(); - } + public void OnDestroy(DbConnection obj) + { + if (obj.State != ConnectionState.Closed) obj.Close(); + obj.Dispose(); + } - public void OnGet(Object obj) { + public void OnGet(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && obj.Value.Ping() == false) + { - try { - obj.Value.OpenAndAttach(Attaches); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + obj.Value.OpenAndAttach(Attaches); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - async public Task OnGetAsync(Object obj) { + async public Task OnGetAsync(Object obj) + { - if (_pool.IsAvailable) { + if (_pool.IsAvailable) + { - if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) { + if (obj.Value.State != ConnectionState.Open || DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 && (await obj.Value.PingAsync()) == false) + { - try { - await obj.Value.OpenAndAttachAsync(Attaches); - } catch (Exception ex) { - if (_pool.SetUnavailable(ex) == true) - throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); - } - } - } - } + try + { + await obj.Value.OpenAndAttachAsync(Attaches); + } + catch (Exception ex) + { + if (_pool.SetUnavailable(ex) == true) + throw new Exception($"【{this.Name}】状态不可用,等待后台检查程序恢复方可使用。{ex.Message}"); + } + } + } + } - public void OnGetTimeout() { + public void OnGetTimeout() + { - } + } - public void OnReturn(Object obj) { + public void OnReturn(Object obj) + { - } + } - public void OnAvailable() { - _pool.availableHandler?.Invoke(); - } + public void OnAvailable() + { + _pool.availableHandler?.Invoke(); + } - public void OnUnavailable() { - _pool.unavailableHandler?.Invoke(); - } - } - static class DbConnectionExtensions { + public void OnUnavailable() + { + _pool.unavailableHandler?.Invoke(); + } + } + static class DbConnectionExtensions + { - static DbCommand PingCommand(DbConnection conn) { - var cmd = conn.CreateCommand(); - cmd.CommandTimeout = 5; - cmd.CommandText = "select 1"; - return cmd; - } - public static bool Ping(this DbConnection that, bool isThrow = false) { - try { - PingCommand(that).ExecuteNonQuery(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } - async public static Task PingAsync(this DbConnection that, bool isThrow = false) { - try { - await PingCommand(that).ExecuteNonQueryAsync(); - return true; - } catch { - if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } - if (isThrow) throw; - return false; - } - } + static DbCommand PingCommand(DbConnection conn) + { + var cmd = conn.CreateCommand(); + cmd.CommandTimeout = 5; + cmd.CommandText = "select 1"; + return cmd; + } + public static bool Ping(this DbConnection that, bool isThrow = false) + { + try + { + PingCommand(that).ExecuteNonQuery(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } + async public static Task PingAsync(this DbConnection that, bool isThrow = false) + { + try + { + await PingCommand(that).ExecuteNonQueryAsync(); + return true; + } + catch + { + if (that.State != ConnectionState.Closed) try { that.Close(); } catch { } + if (isThrow) throw; + return false; + } + } - public static void OpenAndAttach(this DbConnection that, string[] attach) { - that.Open(); + public static void OpenAndAttach(this DbConnection that, string[] attach) + { + that.Open(); - if (attach?.Any() == true) { - var sb = new StringBuilder(); - foreach(var att in attach) - sb.Append($"attach database [{att}] as [{att.Split('.').First()}];\r\n"); + if (attach?.Any() == true) + { + var sb = new StringBuilder(); + foreach (var att in attach) + sb.Append($"attach database [{att}] as [{att.Split('.').First()}];\r\n"); - var cmd = that.CreateCommand(); - cmd.CommandText = sb.ToString(); - cmd.ExecuteNonQuery(); - } - } - async public static Task OpenAndAttachAsync(this DbConnection that, string[] attach) { - await that.OpenAsync(); + var cmd = that.CreateCommand(); + cmd.CommandText = sb.ToString(); + cmd.ExecuteNonQuery(); + } + } + async public static Task OpenAndAttachAsync(this DbConnection that, string[] attach) + { + await that.OpenAsync(); - if (attach?.Any() == true) { - var sb = new StringBuilder(); - foreach (var att in attach) - sb.Append($"attach database [{att}] as [{att.Split('.').First()}];\r\n"); + if (attach?.Any() == true) + { + var sb = new StringBuilder(); + foreach (var att in attach) + sb.Append($"attach database [{att}] as [{att.Split('.').First()}];\r\n"); - var cmd = that.CreateCommand(); - cmd.CommandText = sb.ToString(); - await cmd.ExecuteNonQueryAsync(); - } - } - } + var cmd = that.CreateCommand(); + cmd.CommandText = sb.ToString(); + await cmd.ExecuteNonQueryAsync(); + } + } + } } diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteCodeFirst.cs b/Providers/FreeSql.Provider.Sqlite/SqliteCodeFirst.cs index e3488b89..85d684d4 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteCodeFirst.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteCodeFirst.cs @@ -10,231 +10,267 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; -namespace FreeSql.Sqlite { +namespace FreeSql.Sqlite +{ - class SqliteCodeFirst : Internal.CommonProvider.CodeFirstProvider { + class SqliteCodeFirst : Internal.CommonProvider.CodeFirstProvider + { - public SqliteCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } + public SqliteCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { } - static object _dicCsToDbLock = new object(); - static Dictionary _dicCsToDb = new Dictionary() { - { typeof(bool).FullName, (DbType.Boolean, "boolean","boolean NOT NULL", null, false, false) },{ typeof(bool?).FullName, (DbType.Boolean, "boolean","boolean", null, true, null) }, + static object _dicCsToDbLock = new object(); + static Dictionary _dicCsToDb = new Dictionary() { + { typeof(bool).FullName, (DbType.Boolean, "boolean","boolean NOT NULL", null, false, false) },{ typeof(bool?).FullName, (DbType.Boolean, "boolean","boolean", null, true, null) }, - { typeof(sbyte).FullName, (DbType.SByte, "smallint", "smallint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (DbType.SByte, "smallint", "smallint", false, true, null) }, - { typeof(short).FullName, (DbType.Int16, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, (DbType.Int16, "smallint", "smallint", false, true, null) }, - { typeof(int).FullName, (DbType.Int32, "integer", "integer NOT NULL", false, false, 0) },{ typeof(int?).FullName, (DbType.Int32, "integer", "integer", false, true, null) }, - { typeof(long).FullName, (DbType.Int64, "integer","integer NOT NULL", false, false, 0) },{ typeof(long?).FullName, (DbType.Int64, "integer","integer", false, true, null) }, + { typeof(sbyte).FullName, (DbType.SByte, "smallint", "smallint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, (DbType.SByte, "smallint", "smallint", false, true, null) }, + { typeof(short).FullName, (DbType.Int16, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, (DbType.Int16, "smallint", "smallint", false, true, null) }, + { typeof(int).FullName, (DbType.Int32, "integer", "integer NOT NULL", false, false, 0) },{ typeof(int?).FullName, (DbType.Int32, "integer", "integer", false, true, null) }, + { typeof(long).FullName, (DbType.Int64, "integer","integer NOT NULL", false, false, 0) },{ typeof(long?).FullName, (DbType.Int64, "integer","integer", false, true, null) }, - { typeof(byte).FullName, (DbType.Byte, "int2","int2 NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (DbType.Byte, "int2","int2", true, true, null) }, - { typeof(ushort).FullName, (DbType.UInt16, "unsigned","unsigned NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (DbType.UInt16, "unsigned", "unsigned", true, true, null) }, - { typeof(uint).FullName, (DbType.Decimal, "decimal(10,0)", "decimal(10,0) NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (DbType.Decimal, "decimal(10,0)", "decimal(10,0)", true, true, null) }, - { typeof(ulong).FullName, (DbType.Decimal, "decimal(21,0)", "decimal(21,0) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (DbType.Decimal, "decimal(21,0)", "decimal(21,0)", true, true, null) }, + { typeof(byte).FullName, (DbType.Byte, "int2","int2 NOT NULL", true, false, 0) },{ typeof(byte?).FullName, (DbType.Byte, "int2","int2", true, true, null) }, + { typeof(ushort).FullName, (DbType.UInt16, "unsigned","unsigned NOT NULL", true, false, 0) },{ typeof(ushort?).FullName, (DbType.UInt16, "unsigned", "unsigned", true, true, null) }, + { typeof(uint).FullName, (DbType.Decimal, "decimal(10,0)", "decimal(10,0) NOT NULL", true, false, 0) },{ typeof(uint?).FullName, (DbType.Decimal, "decimal(10,0)", "decimal(10,0)", true, true, null) }, + { typeof(ulong).FullName, (DbType.Decimal, "decimal(21,0)", "decimal(21,0) NOT NULL", true, false, 0) },{ typeof(ulong?).FullName, (DbType.Decimal, "decimal(21,0)", "decimal(21,0)", true, true, null) }, - { typeof(double).FullName, (DbType.Double, "double", "double NOT NULL", false, false, 0) },{ typeof(double?).FullName, (DbType.Double, "double", "double", false, true, null) }, - { typeof(float).FullName, (DbType.Single, "float","float NOT NULL", false, false, 0) },{ typeof(float?).FullName, (DbType.Single, "float","float", false, true, null) }, - { typeof(decimal).FullName, (DbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (DbType.Decimal, "decimal", "decimal(10,2)", false, true, null) }, + { typeof(double).FullName, (DbType.Double, "double", "double NOT NULL", false, false, 0) },{ typeof(double?).FullName, (DbType.Double, "double", "double", false, true, null) }, + { typeof(float).FullName, (DbType.Single, "float","float NOT NULL", false, false, 0) },{ typeof(float?).FullName, (DbType.Single, "float","float", false, true, null) }, + { typeof(decimal).FullName, (DbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, (DbType.Decimal, "decimal", "decimal(10,2)", false, true, null) }, - { typeof(TimeSpan).FullName, (DbType.Time, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (DbType.Time, "bigint", "bigint",false, true, null) }, - { typeof(DateTime).FullName, (DbType.DateTime, "datetime", "datetime NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (DbType.DateTime, "datetime", "datetime", false, true, null) }, + { typeof(TimeSpan).FullName, (DbType.Time, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, (DbType.Time, "bigint", "bigint",false, true, null) }, + { typeof(DateTime).FullName, (DbType.DateTime, "datetime", "datetime NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, (DbType.DateTime, "datetime", "datetime", false, true, null) }, - { typeof(byte[]).FullName, (DbType.Binary, "blob", "blob", false, null, new byte[0]) }, - { typeof(string).FullName, (DbType.String, "nvarchar", "nvarchar(255)", false, null, "") }, + { typeof(byte[]).FullName, (DbType.Binary, "blob", "blob", false, null, new byte[0]) }, + { typeof(string).FullName, (DbType.String, "nvarchar", "nvarchar(255)", false, null, "") }, - { typeof(Guid).FullName, (DbType.Guid, "character", "character(36) NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (DbType.Guid, "character", "character(36)", false, true, null) }, - }; + { typeof(Guid).FullName, (DbType.Guid, "character", "character(36) NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, (DbType.Guid, "character", "character(36)", false, true, null) }, + }; - public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) { - if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); - if (type.IsArray) return null; - var enumType = type.IsEnum ? type : null; - if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); - if (enumType != null) { - var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? - (DbType.Int64, "bigint", $"bigint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : - (DbType.Int32, "mediumint", $"mediumint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); - if (_dicCsToDb.ContainsKey(type.FullName) == false) { - lock (_dicCsToDbLock) { - if (_dicCsToDb.ContainsKey(type.FullName) == false) - _dicCsToDb.Add(type.FullName, newItem); - } - } - return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); - } - return null; - } - - public override string GetComparisonDDLStatements(params Type[] entityTypes) { - var sb = new StringBuilder(); - var sbDeclare = new StringBuilder(); - foreach (var entityType in entityTypes) { - if (sb.Length > 0) sb.Append("\r\n"); - var tb = _commonUtils.GetTableByEntity(entityType); - if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); - if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); - var tbname = tb.DbName.Split(new[] { '.' }, 2); - if (tbname?.Length == 1) tbname = new[] { "main", tbname[0] }; + public override (int type, string dbtype, string dbtypeFull, bool? isnullable, object defaultValue)? GetDbInfo(Type type) + { + if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return new (int, string, string, bool?, object)?(((int)trydc.type, trydc.dbtype, trydc.dbtypeFull, trydc.isnullable, trydc.defaultValue)); + if (type.IsArray) return null; + var enumType = type.IsEnum ? type : null; + if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First(); + if (enumType != null) + { + var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ? + (DbType.Int64, "bigint", $"bigint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)) : + (DbType.Int32, "mediumint", $"mediumint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, Enum.GetValues(enumType).GetValue(0)); + if (_dicCsToDb.ContainsKey(type.FullName) == false) + { + lock (_dicCsToDbLock) + { + if (_dicCsToDb.ContainsKey(type.FullName) == false) + _dicCsToDb.Add(type.FullName, newItem); + } + } + return ((int)newItem.Item1, newItem.Item2, newItem.Item3, newItem.Item5, newItem.Item6); + } + return null; + } - var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名 - if (tboldname?.Length == 1) tboldname = new[] { "main", tboldname[0] }; + public override string GetComparisonDDLStatements(params Type[] entityTypes) + { + var sb = new StringBuilder(); + var sbDeclare = new StringBuilder(); + foreach (var entityType in entityTypes) + { + if (sb.Length > 0) sb.Append("\r\n"); + var tb = _commonUtils.GetTableByEntity(entityType); + if (tb == null) throw new Exception($"类型 {entityType.FullName} 不可迁移"); + if (tb.Columns.Any() == false) throw new Exception($"类型 {entityType.FullName} 不可迁移,可迁移属性0个"); + var tbname = tb.DbName.Split(new[] { '.' }, 2); + if (tbname?.Length == 1) tbname = new[] { "main", tbname[0] }; - var sbalter = new StringBuilder(); - var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 - var isIndent = false; - if (_orm.Ado.ExecuteScalar(CommandType.Text, $" select 1 from {tbname[0]}.sqlite_master where type='table' and name='{tbname[1]}'") == null) { //表不存在 - if (tboldname != null) { - if (_orm.Ado.ExecuteScalar(CommandType.Text, $" select 1 from {tboldname[0]}.sqlite_master where type='table' and name='{tboldname[1]}'") == null) - //模式或表不存在 - tboldname = null; - } - if (tboldname == null) { - //创建表 - sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( "); - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTOINCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) { - isIndent = true; - sb.Append(" PRIMARY KEY AUTOINCREMENT"); - } - sb.Append(","); - } - if (isIndent == false && tb.Primarys.Any()) { - sb.Append(" \r\n PRIMARY KEY ("); - foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1); - sb.Append("\r\n) \r\n;\r\n"); - continue; - } - //如果新表,旧表在一个模式下,直接修改表名 - if (string.Compare(tbname[0], tboldname[0], true) == 0) - sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}")).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append(";\r\n"); - else { - //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 - istmpatler = true; - } - } else - tboldname = null; //如果新表已经存在,不走改表名逻辑 + var tboldname = tb.DbOldName?.Split(new[] { '.' }, 2); //旧表名 + if (tboldname?.Length == 1) tboldname = new[] { "main", tboldname[0] }; - //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 - var tbtmp = tboldname ?? tbname; - var dsql = _orm.Ado.ExecuteScalar(CommandType.Text, $" select sql from {tbtmp[0]}.sqlite_master where type='table' and name='{tbtmp[1]}'")?.ToString(); - var ds = _orm.Ado.ExecuteArray(CommandType.Text, $"PRAGMA {_commonUtils.QuoteSqlName(tbtmp[0])}.table_info({_commonUtils.QuoteSqlName(tbtmp[1])})"); - var tbstruct = ds.ToDictionary(a => string.Concat(a[1]), a => { - var is_identity = false; - var dsqlIdx = dsql?.IndexOf($"\"{a[1]}\" "); - if (dsqlIdx > 0) { - var dsqlLastIdx = dsql.IndexOf('\n', dsqlIdx.Value); - if (dsqlLastIdx > 0) is_identity = dsql.Substring(dsqlIdx.Value, dsqlLastIdx - dsqlIdx.Value).Contains("AUTOINCREMENT"); - } - return new { - column = string.Concat(a[1]), - sqlType = string.Concat(a[2]).ToUpper(), - is_nullable = string.Concat(a[3]) == "0", - is_identity - }; - }, StringComparer.CurrentCultureIgnoreCase); + var sbalter = new StringBuilder(); + var istmpatler = false; //创建临时表,导入数据,删除旧表,修改 + var isIndent = false; + if (_orm.Ado.ExecuteScalar(CommandType.Text, $" select 1 from {tbname[0]}.sqlite_master where type='table' and name='{tbname[1]}'") == null) + { //表不存在 + if (tboldname != null) + { + if (_orm.Ado.ExecuteScalar(CommandType.Text, $" select 1 from {tboldname[0]}.sqlite_master where type='table' and name='{tboldname[1]}'") == null) + //模式或表不存在 + tboldname = null; + } + if (tboldname == null) + { + //创建表 + sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( "); + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); + sb.Append(tbcol.Attribute.DbType); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTOINCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) + { + isIndent = true; + sb.Append(" PRIMARY KEY AUTOINCREMENT"); + } + sb.Append(","); + } + if (isIndent == false && tb.Primarys.Any()) + { + sb.Append(" \r\n PRIMARY KEY ("); + foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1); + sb.Append("\r\n) \r\n;\r\n"); + continue; + } + //如果新表,旧表在一个模式下,直接修改表名 + if (string.Compare(tbname[0], tboldname[0], true) == 0) + sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}")).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append(";\r\n"); + else + { + //如果新表,旧表不在一起,创建新表,导入数据,删除旧表 + istmpatler = true; + } + } + else + tboldname = null; //如果新表已经存在,不走改表名逻辑 - if (istmpatler == false) { - foreach (var tbcol in tb.Columns.Values) { - var dbtypeNoneNotNull = Regex.Replace(tbcol.Attribute.DbType, @"NOT\s+NULL", "NULL"); - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) - istmpatler = true; - if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - istmpatler = true; - if (tbcol.Attribute.IsIdentity != tbstructcol.is_identity) - istmpatler = true; - if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) - //修改列名 - istmpatler = true; - continue; - } - //添加列 - istmpatler = true; - } - var dsukMatches = _regexUK.Matches(dsql); - var dsuk = new List(); - foreach (Match dsukm in dsukMatches) { - var dbsukmg2 = dsukm.Groups[2].Value.Split(','); - if (dbsukmg2.Any() == false) continue; - foreach (var dbfield in dbsukmg2) { - dsuk.Add(new[] { Regex.Match(dbfield, @"""([^""]+)""").Groups[1].Value, dsukm.Groups[1].Value }); - } - } - foreach (var uk in tb.Uniques) { - if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; - var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); - if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) { - istmpatler = true; - } - } - } - if (istmpatler == false) { - sb.Append(sbalter); - continue; - } + //对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段 + var tbtmp = tboldname ?? tbname; + var dsql = _orm.Ado.ExecuteScalar(CommandType.Text, $" select sql from {tbtmp[0]}.sqlite_master where type='table' and name='{tbtmp[1]}'")?.ToString(); + var ds = _orm.Ado.ExecuteArray(CommandType.Text, $"PRAGMA {_commonUtils.QuoteSqlName(tbtmp[0])}.table_info({_commonUtils.QuoteSqlName(tbtmp[1])})"); + var tbstruct = ds.ToDictionary(a => string.Concat(a[1]), a => + { + var is_identity = false; + var dsqlIdx = dsql?.IndexOf($"\"{a[1]}\" "); + if (dsqlIdx > 0) + { + var dsqlLastIdx = dsql.IndexOf('\n', dsqlIdx.Value); + if (dsqlLastIdx > 0) is_identity = dsql.Substring(dsqlIdx.Value, dsqlLastIdx - dsqlIdx.Value).Contains("AUTOINCREMENT"); + } + return new + { + column = string.Concat(a[1]), + sqlType = string.Concat(a[2]).ToUpper(), + is_nullable = string.Concat(a[3]) == "0", + is_identity + }; + }, StringComparer.CurrentCultureIgnoreCase); - //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 - var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"); - var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}._FreeSqlTmp_{tbname[1]}"); - //创建临时表 - //创建表 - isIndent = false; - sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); - foreach (var tbcol in tb.Columns.Values) { - sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); - sb.Append(tbcol.Attribute.DbType); - if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTOINCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) { - isIndent = true; - sb.Append(" PRIMARY KEY AUTOINCREMENT"); - } - sb.Append(","); - } - if (isIndent == false && tb.Primarys.Any()) { - sb.Append(" \r\n PRIMARY KEY ("); - foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - foreach (var uk in tb.Uniques) { - sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); - foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append("),"); - } - sb.Remove(sb.Length - 1, 1); - sb.Append("\r\n) \r\n;\r\n"); - sb.Append("INSERT INTO ").Append(tmptablename).Append(" ("); - foreach (var tbcol in tb.Columns.Values) - sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); - sb.Remove(sb.Length - 2, 2).Append(")\r\nSELECT "); - foreach (var tbcol in tb.Columns.Values) { - var insertvalue = "NULL"; - if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || - string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) { - insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); - if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) { - var dbtypeNoneNotNull = Regex.Replace(tbcol.Attribute.DbType, @"(NOT\s+)?NULL", ""); - insertvalue = $"cast({insertvalue} as {dbtypeNoneNotNull})"; - } - if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) - insertvalue = $"ifnull({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; - } else if (tbcol.Attribute.IsNullable == false) - insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); - sb.Append(insertvalue).Append(", "); - } - sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); - sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n"); - sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append(";\r\n"); - } - return sb.Length == 0 ? null : sb.ToString(); - } - static Regex _regexUK = new Regex(@"CONSTRAINT\s*""([^""]+)""\s*UNIQUE\s*\(([^\)]+)\)", RegexOptions.IgnoreCase | RegexOptions.Compiled); - } + if (istmpatler == false) + { + foreach (var tbcol in tb.Columns.Values) + { + var dbtypeNoneNotNull = Regex.Replace(tbcol.Attribute.DbType, @"NOT\s+NULL", "NULL"); + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) + istmpatler = true; + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) + istmpatler = true; + if (tbcol.Attribute.IsIdentity != tbstructcol.is_identity) + istmpatler = true; + if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) + //修改列名 + istmpatler = true; + continue; + } + //添加列 + istmpatler = true; + } + var dsukMatches = _regexUK.Matches(dsql); + var dsuk = new List(); + foreach (Match dsukm in dsukMatches) + { + var dbsukmg2 = dsukm.Groups[2].Value.Split(','); + if (dbsukmg2.Any() == false) continue; + foreach (var dbfield in dbsukmg2) + { + dsuk.Add(new[] { Regex.Match(dbfield, @"""([^""]+)""").Groups[1].Value, dsukm.Groups[1].Value }); + } + } + foreach (var uk in tb.Uniques) + { + if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue; + var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray(); + if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count) + { + istmpatler = true; + } + } + } + if (istmpatler == false) + { + sb.Append(sbalter); + continue; + } + + //创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名 + var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}"); + var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}._FreeSqlTmp_{tbname[1]}"); + //创建临时表 + //创建表 + isIndent = false; + sb.Append("CREATE TABLE IF NOT EXISTS ").Append(tmptablename).Append(" ( "); + foreach (var tbcol in tb.Columns.Values) + { + sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" "); + sb.Append(tbcol.Attribute.DbType); + if (tbcol.Attribute.IsIdentity == true && tbcol.Attribute.DbType.IndexOf("AUTOINCREMENT", StringComparison.CurrentCultureIgnoreCase) == -1) + { + isIndent = true; + sb.Append(" PRIMARY KEY AUTOINCREMENT"); + } + sb.Append(","); + } + if (isIndent == false && tb.Primarys.Any()) + { + sb.Append(" \r\n PRIMARY KEY ("); + foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + foreach (var uk in tb.Uniques) + { + sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE("); + foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append("),"); + } + sb.Remove(sb.Length - 1, 1); + sb.Append("\r\n) \r\n;\r\n"); + sb.Append("INSERT INTO ").Append(tmptablename).Append(" ("); + foreach (var tbcol in tb.Columns.Values) + sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", "); + sb.Remove(sb.Length - 2, 2).Append(")\r\nSELECT "); + foreach (var tbcol in tb.Columns.Values) + { + var insertvalue = "NULL"; + if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) || + string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol)) + { + insertvalue = _commonUtils.QuoteSqlName(tbstructcol.column); + if (tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false) + { + var dbtypeNoneNotNull = Regex.Replace(tbcol.Attribute.DbType, @"(NOT\s+)?NULL", ""); + insertvalue = $"cast({insertvalue} as {dbtypeNoneNotNull})"; + } + if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable) + insertvalue = $"ifnull({insertvalue},{_commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue)})"; + } + else if (tbcol.Attribute.IsNullable == false) + insertvalue = _commonUtils.FormatSql("{0}", tbcol.Attribute.DbDefautValue); + sb.Append(insertvalue).Append(", "); + } + sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n"); + sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n"); + sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append(";\r\n"); + } + return sb.Length == 0 ? null : sb.ToString(); + } + static Regex _regexUK = new Regex(@"CONSTRAINT\s*""([^""]+)""\s*UNIQUE\s*\(([^\)]+)\)", RegexOptions.IgnoreCase | RegexOptions.Compiled); + } } \ No newline at end of file diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs b/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs index d44576b9..5a0d21a4 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteExpression.cs @@ -7,397 +7,451 @@ using System.Linq; using System.Linq.Expressions; using System.Text; -namespace FreeSql.Sqlite { - class SqliteExpression : CommonExpression { +namespace FreeSql.Sqlite +{ + class SqliteExpression : CommonExpression + { - public SqliteExpression(CommonUtils common) : base(common) { } + public SqliteExpression(CommonUtils common) : base(common) { } - public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.NodeType) { - case ExpressionType.Convert: - var operandExp = (exp as UnaryExpression)?.Operand; - var gentype = exp.Type.NullableTypeOrThis(); - if (gentype != operandExp.Type.NullableTypeOrThis()) { - switch (exp.Type.NullableTypeOrThis().ToString()) { - case "System.Boolean": return $"({getExp(operandExp)} not in ('0','false'))"; - case "System.Byte": return $"cast({getExp(operandExp)} as int2)"; - case "System.Char": return $"substr(cast({getExp(operandExp)} as character), 1, 1)"; - case "System.DateTime": return $"datetime({getExp(operandExp)})"; - case "System.Decimal": return $"cast({getExp(operandExp)} as decimal(36,18))"; - case "System.Double": return $"cast({getExp(operandExp)} as double)"; - case "System.Int16": - case "System.Int32": - case "System.Int64": - case "System.SByte": return $"cast({getExp(operandExp)} as smallint)"; - case "System.Single": return $"cast({getExp(operandExp)} as float)"; - case "System.String": return $"cast({getExp(operandExp)} as character)"; - case "System.UInt16": return $"cast({getExp(operandExp)} as unsigned)"; - case "System.UInt32": return $"cast({getExp(operandExp)} as decimal(10,0))"; - case "System.UInt64": return $"cast({getExp(operandExp)} as decimal(21,0))"; - case "System.Guid": return $"substr(cast({getExp(operandExp)} as character), 1, 36)"; - } - } - break; - case ExpressionType.Call: - var callExp = exp as MethodCallExpression; + public override string ExpressionLambdaToSqlOther(Expression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.NodeType) + { + case ExpressionType.Convert: + var operandExp = (exp as UnaryExpression)?.Operand; + var gentype = exp.Type.NullableTypeOrThis(); + if (gentype != operandExp.Type.NullableTypeOrThis()) + { + switch (exp.Type.NullableTypeOrThis().ToString()) + { + case "System.Boolean": return $"({getExp(operandExp)} not in ('0','false'))"; + case "System.Byte": return $"cast({getExp(operandExp)} as int2)"; + case "System.Char": return $"substr(cast({getExp(operandExp)} as character), 1, 1)"; + case "System.DateTime": return $"datetime({getExp(operandExp)})"; + case "System.Decimal": return $"cast({getExp(operandExp)} as decimal(36,18))"; + case "System.Double": return $"cast({getExp(operandExp)} as double)"; + case "System.Int16": + case "System.Int32": + case "System.Int64": + case "System.SByte": return $"cast({getExp(operandExp)} as smallint)"; + case "System.Single": return $"cast({getExp(operandExp)} as float)"; + case "System.String": return $"cast({getExp(operandExp)} as character)"; + case "System.UInt16": return $"cast({getExp(operandExp)} as unsigned)"; + case "System.UInt32": return $"cast({getExp(operandExp)} as decimal(10,0))"; + case "System.UInt64": return $"cast({getExp(operandExp)} as decimal(21,0))"; + case "System.Guid": return $"substr(cast({getExp(operandExp)} as character), 1, 36)"; + } + } + break; + case ExpressionType.Call: + var callExp = exp as MethodCallExpression; - switch (callExp.Method.Name) { - case "Parse": - case "TryParse": - switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) { - case "System.Boolean": return $"({getExp(callExp.Arguments[0])} not in ('0','false'))"; - case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as int2)"; - case "System.Char": return $"substr(cast({getExp(callExp.Arguments[0])} as character), 1, 1)"; - case "System.DateTime": return $"datetime({getExp(callExp.Arguments[0])})"; - case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as decimal(36,18))"; - case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as double)"; - case "System.Int16": - case "System.Int32": - case "System.Int64": - case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as smallint)"; - case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as float)"; - case "System.UInt16": return $"cast({getExp(callExp.Arguments[0])} as unsigned)"; - case "System.UInt32": return $"cast({getExp(callExp.Arguments[0])} as decimal(10,0))"; - case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as decimal(21,0))"; - case "System.Guid": return $"substr(cast({getExp(callExp.Arguments[0])} as character), 1, 36)"; - } - break; - case "NewGuid": - break; - case "Next": - if (callExp.Object?.Type == typeof(Random)) return "cast(random()*1000000000 as int)"; - break; - case "NextDouble": - if (callExp.Object?.Type == typeof(Random)) return "random()"; - break; - case "Random": - if (callExp.Method.DeclaringType.IsNumberType()) return "random()"; - break; - case "ToString": - if (callExp.Object != null) return $"cast({getExp(callExp.Object)} as character)"; - break; - } + switch (callExp.Method.Name) + { + case "Parse": + case "TryParse": + switch (callExp.Method.DeclaringType.NullableTypeOrThis().ToString()) + { + case "System.Boolean": return $"({getExp(callExp.Arguments[0])} not in ('0','false'))"; + case "System.Byte": return $"cast({getExp(callExp.Arguments[0])} as int2)"; + case "System.Char": return $"substr(cast({getExp(callExp.Arguments[0])} as character), 1, 1)"; + case "System.DateTime": return $"datetime({getExp(callExp.Arguments[0])})"; + case "System.Decimal": return $"cast({getExp(callExp.Arguments[0])} as decimal(36,18))"; + case "System.Double": return $"cast({getExp(callExp.Arguments[0])} as double)"; + case "System.Int16": + case "System.Int32": + case "System.Int64": + case "System.SByte": return $"cast({getExp(callExp.Arguments[0])} as smallint)"; + case "System.Single": return $"cast({getExp(callExp.Arguments[0])} as float)"; + case "System.UInt16": return $"cast({getExp(callExp.Arguments[0])} as unsigned)"; + case "System.UInt32": return $"cast({getExp(callExp.Arguments[0])} as decimal(10,0))"; + case "System.UInt64": return $"cast({getExp(callExp.Arguments[0])} as decimal(21,0))"; + case "System.Guid": return $"substr(cast({getExp(callExp.Arguments[0])} as character), 1, 36)"; + } + break; + case "NewGuid": + break; + case "Next": + if (callExp.Object?.Type == typeof(Random)) return "cast(random()*1000000000 as int)"; + break; + case "NextDouble": + if (callExp.Object?.Type == typeof(Random)) return "random()"; + break; + case "Random": + if (callExp.Method.DeclaringType.IsNumberType()) return "random()"; + break; + case "ToString": + if (callExp.Object != null) return $"cast({getExp(callExp.Object)} as character)"; + break; + } - var objExp = callExp.Object; - var objType = objExp?.Type; - if (objType?.FullName == "System.Byte[]") return null; + var objExp = callExp.Object; + var objType = objExp?.Type; + if (objType?.FullName == "System.Byte[]") return null; - var argIndex = 0; - if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) { - objExp = callExp.Arguments.FirstOrDefault(); - objType = objExp?.Type; - argIndex++; - } - if (objType == null) objType = callExp.Method.DeclaringType; - if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) { - var left = objExp == null ? null : getExp(objExp); - switch (callExp.Method.Name) { - case "Contains": - //判断 in - return $"({getExp(callExp.Arguments[argIndex])}) in {left}"; - } - } - break; - case ExpressionType.NewArrayInit: - var arrExp = exp as NewArrayExpression; - var arrSb = new StringBuilder(); - arrSb.Append("("); - for (var a = 0; a < arrExp.Expressions.Count; a++) { - if (a > 0) arrSb.Append(","); - arrSb.Append(getExp(arrExp.Expressions[a])); - } - if (arrSb.Length == 1) arrSb.Append("NULL"); - return arrSb.Append(")").ToString(); - case ExpressionType.ListInit: - var listExp = exp as ListInitExpression; - var listSb = new StringBuilder(); - listSb.Append("("); - for (var a = 0; a < listExp.Initializers.Count; a++) { - if (listExp.Initializers[a].Arguments.Any() == false) continue; - if (a > 0) listSb.Append(","); - listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); - } - if (listSb.Length == 1) listSb.Append("NULL"); - return listSb.Append(")").ToString(); - case ExpressionType.New: - var newExp = exp as NewExpression; - if (typeof(IList).IsAssignableFrom(newExp.Type)) { - if (newExp.Arguments.Count == 0) return "(NULL)"; - if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; - return getExp(newExp.Arguments[0]); - } - return null; - } - return null; - } + var argIndex = 0; + if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable)) + { + objExp = callExp.Arguments.FirstOrDefault(); + objType = objExp?.Type; + argIndex++; + } + if (objType == null) objType = callExp.Method.DeclaringType; + if (objType != null || objType.IsArray || typeof(IList).IsAssignableFrom(callExp.Method.DeclaringType)) + { + var left = objExp == null ? null : getExp(objExp); + switch (callExp.Method.Name) + { + case "Contains": + //判断 in + return $"({getExp(callExp.Arguments[argIndex])}) in {left}"; + } + } + break; + case ExpressionType.NewArrayInit: + var arrExp = exp as NewArrayExpression; + var arrSb = new StringBuilder(); + arrSb.Append("("); + for (var a = 0; a < arrExp.Expressions.Count; a++) + { + if (a > 0) arrSb.Append(","); + arrSb.Append(getExp(arrExp.Expressions[a])); + } + if (arrSb.Length == 1) arrSb.Append("NULL"); + return arrSb.Append(")").ToString(); + case ExpressionType.ListInit: + var listExp = exp as ListInitExpression; + var listSb = new StringBuilder(); + listSb.Append("("); + for (var a = 0; a < listExp.Initializers.Count; a++) + { + if (listExp.Initializers[a].Arguments.Any() == false) continue; + if (a > 0) listSb.Append(","); + listSb.Append(getExp(listExp.Initializers[a].Arguments.FirstOrDefault())); + } + if (listSb.Length == 1) listSb.Append("NULL"); + return listSb.Append(")").ToString(); + case ExpressionType.New: + var newExp = exp as NewExpression; + if (typeof(IList).IsAssignableFrom(newExp.Type)) + { + if (newExp.Arguments.Count == 0) return "(NULL)"; + if (typeof(IEnumerable).IsAssignableFrom(newExp.Arguments[0].Type) == false) return "(NULL)"; + return getExp(newExp.Arguments[0]); + } + return null; + } + return null; + } - public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Empty": return "''"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Length": return $"length({left})"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Now": return "datetime(current_timestamp,'localtime')"; - case "UtcNow": return "current_timestamp"; - case "Today": return "date(current_timestamp,'localtime')"; - case "MinValue": return "datetime('0001-01-01 00:00:00.000')"; - case "MaxValue": return "datetime('9999-12-31 23:59:59.999')"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Date": return $"date({left})"; - case "TimeOfDay": return $"strftime('%s',{left})"; - case "DayOfWeek": return $"strftime('%w',{left})"; - case "Day": return $"strftime('%d',{left})"; - case "DayOfYear": return $"strftime('%j',{left})"; - case "Month": return $"strftime('%m',{left})"; - case "Year": return $"strftime('%Y',{left})"; - case "Hour": return $"strftime('%H',{left})"; - case "Minute": return $"strftime('%M',{left})"; - case "Second": return $"strftime('%S',{left})"; - case "Millisecond": return $"(strftime('%f',{left})-strftime('%S',{left}))"; - case "Ticks": return $"(strftime('%s',{left})*10000000+621355968000000000)"; - } - return null; - } - public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) { - if (exp.Expression == null) { - switch (exp.Member.Name) { - case "Zero": return "0"; - case "MinValue": return "-922337203685.477580"; //秒 Ticks / 1000,000,0 - case "MaxValue": return "922337203685.477580"; - } - return null; - } - var left = ExpressionLambdaToSql(exp.Expression, tsc); - switch (exp.Member.Name) { - case "Days": return $"floor(({left})/{60 * 60 * 24})"; - case "Hours": return $"floor(({left})/{60 * 60}%24)"; - case "Milliseconds": return $"(cast({left} as bigint)*1000)"; - case "Minutes": return $"floor(({left})/60%60)"; - case "Seconds": return $"(({left})%60)"; - case "Ticks": return $"(cast({left} as bigint)*10000000)"; - case "TotalDays": return $"(({left})/{60 * 60 * 24})"; - case "TotalHours": return $"(({left})/{60 * 60})"; - case "TotalMilliseconds": return $"(cast({left} as bigint)*1000)"; - case "TotalMinutes": return $"(({left})/60)"; - case "TotalSeconds": return $"({left})"; - } - return null; - } + public override string ExpressionLambdaToSqlMemberAccessString(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Empty": return "''"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Length": return $"length({left})"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessDateTime(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Now": return "datetime(current_timestamp,'localtime')"; + case "UtcNow": return "current_timestamp"; + case "Today": return "date(current_timestamp,'localtime')"; + case "MinValue": return "datetime('0001-01-01 00:00:00.000')"; + case "MaxValue": return "datetime('9999-12-31 23:59:59.999')"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Date": return $"date({left})"; + case "TimeOfDay": return $"strftime('%s',{left})"; + case "DayOfWeek": return $"strftime('%w',{left})"; + case "Day": return $"strftime('%d',{left})"; + case "DayOfYear": return $"strftime('%j',{left})"; + case "Month": return $"strftime('%m',{left})"; + case "Year": return $"strftime('%Y',{left})"; + case "Hour": return $"strftime('%H',{left})"; + case "Minute": return $"strftime('%M',{left})"; + case "Second": return $"strftime('%S',{left})"; + case "Millisecond": return $"(strftime('%f',{left})-strftime('%S',{left}))"; + case "Ticks": return $"(strftime('%s',{left})*10000000+621355968000000000)"; + } + return null; + } + public override string ExpressionLambdaToSqlMemberAccessTimeSpan(MemberExpression exp, ExpTSC tsc) + { + if (exp.Expression == null) + { + switch (exp.Member.Name) + { + case "Zero": return "0"; + case "MinValue": return "-922337203685.477580"; //秒 Ticks / 1000,000,0 + case "MaxValue": return "922337203685.477580"; + } + return null; + } + var left = ExpressionLambdaToSql(exp.Expression, tsc); + switch (exp.Member.Name) + { + case "Days": return $"floor(({left})/{60 * 60 * 24})"; + case "Hours": return $"floor(({left})/{60 * 60}%24)"; + case "Milliseconds": return $"(cast({left} as bigint)*1000)"; + case "Minutes": return $"floor(({left})/60%60)"; + case "Seconds": return $"(({left})%60)"; + case "Ticks": return $"(cast({left} as bigint)*10000000)"; + case "TotalDays": return $"(({left})/{60 * 60 * 24})"; + case "TotalHours": return $"(({left})/{60 * 60})"; + case "TotalMilliseconds": return $"(cast({left} as bigint)*1000)"; + case "TotalMinutes": return $"(({left})/60)"; + case "TotalSeconds": return $"({left})"; + } + return null; + } - public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "IsNullOrEmpty": - var arg1 = getExp(exp.Arguments[0]); - return $"({arg1} is null or {arg1} = '')"; - case "Concat": - return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); - } - } else { - var left = getExp(exp.Object); - switch (exp.Method.Name) { - case "StartsWith": - case "EndsWith": - case "Contains": - var args0Value = getExp(exp.Arguments[0]); - if (args0Value == "NULL") return $"({left}) IS NULL"; - if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"({args0Value})||'%'")}"; - if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"'%'||({args0Value})")}"; - if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; - return $"({left}) LIKE '%'||({args0Value})||'%'"; - case "ToLower": return $"lower({left})"; - case "ToUpper": return $"upper({left})"; - case "Substring": - var substrArgs1 = getExp(exp.Arguments[0]); - if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); - else substrArgs1 += "+1"; - if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; - return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; - case "IndexOf": - var indexOfFindStr = getExp(exp.Arguments[0]); - //if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") { - // var locateArgs1 = getExp(exp.Arguments[1]); - // if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); - // else locateArgs1 += "+1"; - // return $"(instr({left}, {indexOfFindStr}, {locateArgs1})-1)"; - //} - return $"(instr({left}, {indexOfFindStr})-1)"; - case "PadLeft": - if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})"; - return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "PadRight": - if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})"; - return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Trim": - case "TrimStart": - case "TrimEnd": - if (exp.Arguments.Count == 0) { - if (exp.Method.Name == "Trim") return $"trim({left})"; - if (exp.Method.Name == "TrimStart") return $"ltrim({left})"; - if (exp.Method.Name == "TrimEnd") return $"rtrim({left})"; - } - var trimArg1 = ""; - var trimArg2 = ""; - foreach (var argsTrim02 in exp.Arguments) { - var argsTrim01s = new[] { argsTrim02 }; - if (argsTrim02.NodeType == ExpressionType.NewArrayInit) { - var arritem = argsTrim02 as NewArrayExpression; - argsTrim01s = arritem.Expressions.ToArray(); - } - foreach (var argsTrim01 in argsTrim01s) { - var trimChr = getExp(argsTrim01).Trim('\''); - if (trimChr.Length == 1) trimArg1 += trimChr; - else trimArg2 += $" || ({trimChr})"; - } - } - if (exp.Method.Name == "Trim") left = $"trim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; - if (exp.Method.Name == "TrimStart") left = $"ltrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; - if (exp.Method.Name == "TrimEnd") left = $"rtrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; - return left; - case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "CompareTo": return $"case when {left} = {getExp(exp.Arguments[0])} then 0 when {left} > {getExp(exp.Arguments[0])} then 1 else -1 end"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - } - } - throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - switch (exp.Method.Name) { - case "Abs": return $"abs({getExp(exp.Arguments[0])})"; - case "Sign": return $"sign({getExp(exp.Arguments[0])})"; - case "Floor": return $"floor({getExp(exp.Arguments[0])})"; - case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})"; - case "Round": - if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - return $"round({getExp(exp.Arguments[0])})"; - case "Exp": return $"exp({getExp(exp.Arguments[0])})"; - case "Log": return $"log({getExp(exp.Arguments[0])})"; - case "Log10": return $"log10({getExp(exp.Arguments[0])})"; - case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; - case "Cos": return $"cos({getExp(exp.Arguments[0])})"; - case "Sin": return $"sin({getExp(exp.Arguments[0])})"; - case "Tan": return $"tan({getExp(exp.Arguments[0])})"; - case "Acos": return $"acos({getExp(exp.Arguments[0])})"; - case "Asin": return $"asin({getExp(exp.Arguments[0])})"; - case "Atan": return $"atan({getExp(exp.Arguments[0])})"; - case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; - //case "Truncate": return $"truncate({getExp(exp.Arguments[0])}, 0)"; - } - throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"(strftime('%s',{getExp(exp.Arguments[0])}) -strftime('%s',{getExp(exp.Arguments[1])}))"; - case "DaysInMonth": return $"strftime('%d',date({getExp(exp.Arguments[0])}||'-01-01',{getExp(exp.Arguments[1])}||' months','-1 days'))"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + public override string ExpressionLambdaToSqlCallString(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "IsNullOrEmpty": + var arg1 = getExp(exp.Arguments[0]); + return $"({arg1} is null or {arg1} = '')"; + case "Concat": + return _common.StringConcat(exp.Arguments.Select(a => getExp(a)).ToArray(), null); + } + } + else + { + var left = getExp(exp.Object); + switch (exp.Method.Name) + { + case "StartsWith": + case "EndsWith": + case "Contains": + var args0Value = getExp(exp.Arguments[0]); + if (args0Value == "NULL") return $"({left}) IS NULL"; + if (exp.Method.Name == "StartsWith") return $"({left}) LIKE {(args0Value.EndsWith("'") ? args0Value.Insert(args0Value.Length - 1, "%") : $"({args0Value})||'%'")}"; + if (exp.Method.Name == "EndsWith") return $"({left}) LIKE {(args0Value.StartsWith("'") ? args0Value.Insert(1, "%") : $"'%'||({args0Value})")}"; + if (args0Value.StartsWith("'") && args0Value.EndsWith("'")) return $"({left}) LIKE {args0Value.Insert(1, "%").Insert(args0Value.Length, "%")}"; + return $"({left}) LIKE '%'||({args0Value})||'%'"; + case "ToLower": return $"lower({left})"; + case "ToUpper": return $"upper({left})"; + case "Substring": + var substrArgs1 = getExp(exp.Arguments[0]); + if (long.TryParse(substrArgs1, out var testtrylng1)) substrArgs1 = (testtrylng1 + 1).ToString(); + else substrArgs1 += "+1"; + if (exp.Arguments.Count == 1) return $"substr({left}, {substrArgs1})"; + return $"substr({left}, {substrArgs1}, {getExp(exp.Arguments[1])})"; + case "IndexOf": + var indexOfFindStr = getExp(exp.Arguments[0]); + //if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") { + // var locateArgs1 = getExp(exp.Arguments[1]); + // if (long.TryParse(locateArgs1, out var testtrylng2)) locateArgs1 = (testtrylng2 + 1).ToString(); + // else locateArgs1 += "+1"; + // return $"(instr({left}, {indexOfFindStr}, {locateArgs1})-1)"; + //} + return $"(instr({left}, {indexOfFindStr})-1)"; + case "PadLeft": + if (exp.Arguments.Count == 1) return $"lpad({left}, {getExp(exp.Arguments[0])})"; + return $"lpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "PadRight": + if (exp.Arguments.Count == 1) return $"rpad({left}, {getExp(exp.Arguments[0])})"; + return $"rpad({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Trim": + case "TrimStart": + case "TrimEnd": + if (exp.Arguments.Count == 0) + { + if (exp.Method.Name == "Trim") return $"trim({left})"; + if (exp.Method.Name == "TrimStart") return $"ltrim({left})"; + if (exp.Method.Name == "TrimEnd") return $"rtrim({left})"; + } + var trimArg1 = ""; + var trimArg2 = ""; + foreach (var argsTrim02 in exp.Arguments) + { + var argsTrim01s = new[] { argsTrim02 }; + if (argsTrim02.NodeType == ExpressionType.NewArrayInit) + { + var arritem = argsTrim02 as NewArrayExpression; + argsTrim01s = arritem.Expressions.ToArray(); + } + foreach (var argsTrim01 in argsTrim01s) + { + var trimChr = getExp(argsTrim01).Trim('\''); + if (trimChr.Length == 1) trimArg1 += trimChr; + else trimArg2 += $" || ({trimChr})"; + } + } + if (exp.Method.Name == "Trim") left = $"trim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; + if (exp.Method.Name == "TrimStart") left = $"ltrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; + if (exp.Method.Name == "TrimEnd") left = $"rtrim({left}, {_common.FormatSql("{0}", trimArg1)}{trimArg2})"; + return left; + case "Replace": return $"replace({left}, {getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "CompareTo": return $"case when {left} = {getExp(exp.Arguments[0])} then 0 when {left} > {getExp(exp.Arguments[0])} then 1 else -1 end"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + } + } + throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallMath(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + switch (exp.Method.Name) + { + case "Abs": return $"abs({getExp(exp.Arguments[0])})"; + case "Sign": return $"sign({getExp(exp.Arguments[0])})"; + case "Floor": return $"floor({getExp(exp.Arguments[0])})"; + case "Ceiling": return $"ceiling({getExp(exp.Arguments[0])})"; + case "Round": + if (exp.Arguments.Count > 1 && exp.Arguments[1].Type.FullName == "System.Int32") return $"round({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + return $"round({getExp(exp.Arguments[0])})"; + case "Exp": return $"exp({getExp(exp.Arguments[0])})"; + case "Log": return $"log({getExp(exp.Arguments[0])})"; + case "Log10": return $"log10({getExp(exp.Arguments[0])})"; + case "Pow": return $"power({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + case "Sqrt": return $"sqrt({getExp(exp.Arguments[0])})"; + case "Cos": return $"cos({getExp(exp.Arguments[0])})"; + case "Sin": return $"sin({getExp(exp.Arguments[0])})"; + case "Tan": return $"tan({getExp(exp.Arguments[0])})"; + case "Acos": return $"acos({getExp(exp.Arguments[0])})"; + case "Asin": return $"asin({getExp(exp.Arguments[0])})"; + case "Atan": return $"atan({getExp(exp.Arguments[0])})"; + case "Atan2": return $"atan2({getExp(exp.Arguments[0])}, {getExp(exp.Arguments[1])})"; + //case "Truncate": return $"truncate({getExp(exp.Arguments[0])}, 0)"; + } + throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallDateTime(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"(strftime('%s',{getExp(exp.Arguments[0])}) -strftime('%s',{getExp(exp.Arguments[1])}))"; + case "DaysInMonth": return $"strftime('%d',date({getExp(exp.Arguments[0])}||'-01-01',{getExp(exp.Arguments[1])}||' months','-1 days'))"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "IsLeapYear": - var isLeapYearArgs1 = getExp(exp.Arguments[0]); - return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)"; + case "IsLeapYear": + var isLeapYearArgs1 = getExp(exp.Arguments[0]); + return $"(({isLeapYearArgs1})%4=0 AND ({isLeapYearArgs1})%100<>0 OR ({isLeapYearArgs1})%400=0)"; - case "Parse": return $"datetime({getExp(exp.Arguments[0])})"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"datetime({getExp(exp.Arguments[0])})"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"datetime({left},({args1})||' seconds')"; - case "AddDays": return $"datetime({left},({args1})||' days')"; - case "AddHours": return $"datetime({left},({args1})||' hours')"; - case "AddMilliseconds": return $"datetime({left},(({args1})/1000)||' seconds')"; - case "AddMinutes": return $"datetime({left},({args1})||' seconds')"; - case "AddMonths": return $"datetime({left},({args1})||' months')"; - case "AddSeconds": return $"datetime({left},({args1})||' seconds')"; - case "AddTicks": return $"datetime({left},(({args1})/10000000)||' seconds')"; - case "AddYears": return $"datetime({left},({args1})||' years')"; - case "Subtract": - switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) { - case "System.DateTime": return $"(strftime('%s',{left})-strftime('%s',{args1}))"; - case "System.TimeSpan": return $"datetime({left},(-{args1})||' seconds')"; - } - break; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"(strftime('%s',{left})-strftime('%s',{args1}))"; - case "ToString": return $"strftime('%Y-%m-%d %H:%M.%f',{left})"; - } - } - throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))"; - case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; - case "FromDays": return $"(({getExp(exp.Arguments[0])})*{60 * 60 * 24})"; - case "FromHours": return $"(({getExp(exp.Arguments[0])})*{60 * 60})"; - case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})/1000)"; - case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*60)"; - case "FromSeconds": return $"(({getExp(exp.Arguments[0])}))"; - case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10000000)"; - case "Parse": return $"cast({getExp(exp.Arguments[0])} as bigint)"; - case "ParseExact": - case "TryParse": - case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as bigint)"; - } - } else { - var left = getExp(exp.Object); - var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); - switch (exp.Method.Name) { - case "Add": return $"({left}+{args1})"; - case "Subtract": return $"({left}-({args1}))"; - case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; - case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))"; - case "ToString": return $"cast({left} as character)"; - } - } - throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); - } - public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) { - Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); - if (exp.Object == null) { - switch (exp.Method.Name) { - case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))"; - case "ToByte": return $"cast({getExp(exp.Arguments[0])} as int2)"; - case "ToChar": return $"substr(cast({getExp(exp.Arguments[0])} as character), 1, 1)"; - case "ToDateTime": return $"datetime({getExp(exp.Arguments[0])})"; - case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))"; - case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as double)"; - case "ToInt16": - case "ToInt32": - case "ToInt64": - case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as smallint)"; - case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as float)"; - case "ToString": return $"cast({getExp(exp.Arguments[0])} as character)"; - case "ToUInt16": return $"cast({getExp(exp.Arguments[0])} as unsigned)"; - case "ToUInt32": return $"cast({getExp(exp.Arguments[0])} as decimal(10,0))"; - case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as decimal(21,0))"; - } - } - throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); - } - } + case "Parse": return $"datetime({getExp(exp.Arguments[0])})"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"datetime({getExp(exp.Arguments[0])})"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"datetime({left},({args1})||' seconds')"; + case "AddDays": return $"datetime({left},({args1})||' days')"; + case "AddHours": return $"datetime({left},({args1})||' hours')"; + case "AddMilliseconds": return $"datetime({left},(({args1})/1000)||' seconds')"; + case "AddMinutes": return $"datetime({left},({args1})||' seconds')"; + case "AddMonths": return $"datetime({left},({args1})||' months')"; + case "AddSeconds": return $"datetime({left},({args1})||' seconds')"; + case "AddTicks": return $"datetime({left},(({args1})/10000000)||' seconds')"; + case "AddYears": return $"datetime({left},({args1})||' years')"; + case "Subtract": + switch ((exp.Arguments[0].Type.IsNullableType() ? exp.Arguments[0].Type.GenericTypeArguments.FirstOrDefault() : exp.Arguments[0].Type).FullName) + { + case "System.DateTime": return $"(strftime('%s',{left})-strftime('%s',{args1}))"; + case "System.TimeSpan": return $"datetime({left},(-{args1})||' seconds')"; + } + break; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"(strftime('%s',{left})-strftime('%s',{args1}))"; + case "ToString": return $"strftime('%Y-%m-%d %H:%M.%f',{left})"; + } + } + throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallTimeSpan(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "Compare": return $"({getExp(exp.Arguments[0])}-({getExp(exp.Arguments[1])}))"; + case "Equals": return $"({getExp(exp.Arguments[0])} = {getExp(exp.Arguments[1])})"; + case "FromDays": return $"(({getExp(exp.Arguments[0])})*{60 * 60 * 24})"; + case "FromHours": return $"(({getExp(exp.Arguments[0])})*{60 * 60})"; + case "FromMilliseconds": return $"(({getExp(exp.Arguments[0])})/1000)"; + case "FromMinutes": return $"(({getExp(exp.Arguments[0])})*60)"; + case "FromSeconds": return $"(({getExp(exp.Arguments[0])}))"; + case "FromTicks": return $"(({getExp(exp.Arguments[0])})/10000000)"; + case "Parse": return $"cast({getExp(exp.Arguments[0])} as bigint)"; + case "ParseExact": + case "TryParse": + case "TryParseExact": return $"cast({getExp(exp.Arguments[0])} as bigint)"; + } + } + else + { + var left = getExp(exp.Object); + var args1 = exp.Arguments.Count == 0 ? null : getExp(exp.Arguments[0]); + switch (exp.Method.Name) + { + case "Add": return $"({left}+{args1})"; + case "Subtract": return $"({left}-({args1}))"; + case "Equals": return $"({left} = {getExp(exp.Arguments[0])})"; + case "CompareTo": return $"({left}-({getExp(exp.Arguments[0])}))"; + case "ToString": return $"cast({left} as character)"; + } + } + throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); + } + public override string ExpressionLambdaToSqlCallConvert(MethodCallExpression exp, ExpTSC tsc) + { + Func getExp = exparg => ExpressionLambdaToSql(exparg, tsc); + if (exp.Object == null) + { + switch (exp.Method.Name) + { + case "ToBoolean": return $"({getExp(exp.Arguments[0])} not in ('0','false'))"; + case "ToByte": return $"cast({getExp(exp.Arguments[0])} as int2)"; + case "ToChar": return $"substr(cast({getExp(exp.Arguments[0])} as character), 1, 1)"; + case "ToDateTime": return $"datetime({getExp(exp.Arguments[0])})"; + case "ToDecimal": return $"cast({getExp(exp.Arguments[0])} as decimal(36,18))"; + case "ToDouble": return $"cast({getExp(exp.Arguments[0])} as double)"; + case "ToInt16": + case "ToInt32": + case "ToInt64": + case "ToSByte": return $"cast({getExp(exp.Arguments[0])} as smallint)"; + case "ToSingle": return $"cast({getExp(exp.Arguments[0])} as float)"; + case "ToString": return $"cast({getExp(exp.Arguments[0])} as character)"; + case "ToUInt16": return $"cast({getExp(exp.Arguments[0])} as unsigned)"; + case "ToUInt32": return $"cast({getExp(exp.Arguments[0])} as decimal(10,0))"; + case "ToUInt64": return $"cast({getExp(exp.Arguments[0])} as decimal(21,0))"; + } + } + throw new Exception($"SqliteExpression 未实现函数表达式 {exp} 解析"); + } + } } diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteExtensions.cs b/Providers/FreeSql.Provider.Sqlite/SqliteExtensions.cs index c9224c1b..a988dd50 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteExtensions.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteExtensions.cs @@ -1,11 +1,12 @@ -public static partial class FreeSqlGlobalExtensions { +public static partial class FreeSqlGlobalExtensions +{ - /// - /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 - /// - /// - /// - /// - public static string FormatSqlite (this string that, params object[] args) => _sqliteAdo.Addslashes(that, args); - static FreeSql.Sqlite.SqliteAdo _sqliteAdo = new FreeSql.Sqlite.SqliteAdo(); + /// + /// 特殊处理类似 string.Format 的使用方法,防止注入,以及 IS NULL 转换 + /// + /// + /// + /// + public static string FormatSqlite(this string that, params object[] args) => _sqliteAdo.Addslashes(that, args); + static FreeSql.Sqlite.SqliteAdo _sqliteAdo = new FreeSql.Sqlite.SqliteAdo(); } diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteProvider.cs b/Providers/FreeSql.Provider.Sqlite/SqliteProvider.cs index 73948db3..7ecf5db6 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteProvider.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteProvider.cs @@ -5,49 +5,54 @@ using System; using System.Collections.Generic; using System.Data.Common; -namespace FreeSql.Sqlite { +namespace FreeSql.Sqlite +{ - public class SqliteProvider : IFreeSql { + public class SqliteProvider : IFreeSql + { - public ISelect Select() where T1 : class => new SqliteSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public ISelect Select(object dywhere) where T1 : class => new SqliteSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IInsert Insert() where T1 : class => new SqliteInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); - public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); - public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); - public IUpdate Update() where T1 : class => new SqliteUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IUpdate Update(object dywhere) where T1 : class => new SqliteUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IDelete Delete() where T1 : class => new SqliteDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); - public IDelete Delete(object dywhere) where T1 : class => new SqliteDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public ISelect Select() where T1 : class => new SqliteSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public ISelect Select(object dywhere) where T1 : class => new SqliteSelect(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IInsert Insert() where T1 : class => new SqliteInsert(this, this.InternalCommonUtils, this.InternalCommonExpression); + public IInsert Insert(T1 source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(T1[] source) where T1 : class => this.Insert().AppendData(source); + public IInsert Insert(IEnumerable source) where T1 : class => this.Insert().AppendData(source); + public IUpdate Update() where T1 : class => new SqliteUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IUpdate Update(object dywhere) where T1 : class => new SqliteUpdate(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); + public IDelete Delete() where T1 : class => new SqliteDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, null); + public IDelete Delete(object dywhere) where T1 : class => new SqliteDelete(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); - public IAdo Ado { get; } - public IAop Aop { get; } - public ICodeFirst CodeFirst { get; } - public IDbFirst DbFirst => null; - public SqliteProvider(string masterConnectionString, string[] slaveConnectionString) { - this.InternalCommonUtils = new SqliteUtils(this); - this.InternalCommonExpression = new SqliteExpression(this.InternalCommonUtils); + public IAdo Ado { get; } + public IAop Aop { get; } + public ICodeFirst CodeFirst { get; } + public IDbFirst DbFirst => null; + public SqliteProvider(string masterConnectionString, string[] slaveConnectionString) + { + this.InternalCommonUtils = new SqliteUtils(this); + this.InternalCommonExpression = new SqliteExpression(this.InternalCommonUtils); - this.Ado = new SqliteAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); - this.Aop = new AopProvider(); + this.Ado = new SqliteAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString); + this.Aop = new AopProvider(); - this.CodeFirst = new SqliteCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); - } + this.CodeFirst = new SqliteCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); + } - internal CommonUtils InternalCommonUtils { get; } - internal CommonExpression InternalCommonExpression { get; } + internal CommonUtils InternalCommonUtils { get; } + internal CommonExpression InternalCommonExpression { get; } - public void Transaction(Action handler) => Ado.Transaction(handler); + public void Transaction(Action handler) => Ado.Transaction(handler); - public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); + public void Transaction(Action handler, TimeSpan timeout) => Ado.Transaction(handler, timeout); - ~SqliteProvider() { - this.Dispose(); - } - bool _isdisposed = false; - public void Dispose() { - if (_isdisposed) return; - (this.Ado as AdoProvider)?.Dispose(); - } - } + ~SqliteProvider() + { + this.Dispose(); + } + bool _isdisposed = false; + public void Dispose() + { + if (_isdisposed) return; + (this.Ado as AdoProvider)?.Dispose(); + } + } } diff --git a/Providers/FreeSql.Provider.Sqlite/SqliteUtils.cs b/Providers/FreeSql.Provider.Sqlite/SqliteUtils.cs index dc3e633c..0ce0b722 100644 --- a/Providers/FreeSql.Provider.Sqlite/SqliteUtils.cs +++ b/Providers/FreeSql.Provider.Sqlite/SqliteUtils.cs @@ -8,76 +8,86 @@ using System.Data.SQLite; using System.Linq.Expressions; using System.Text; -namespace FreeSql.Sqlite { +namespace FreeSql.Sqlite +{ - class SqliteUtils : CommonUtils { - public SqliteUtils(IFreeSql orm) : base(orm) { - } + class SqliteUtils : CommonUtils + { + public SqliteUtils(IFreeSql orm) : base(orm) + { + } - public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) { - if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; - var dbtype = (DbType)_orm.CodeFirst.GetDbInfo(type)?.type; - switch (dbtype) { - case DbType.Guid: - if (value == null) value = null; - else value = ((Guid)value).ToString(); - dbtype = DbType.String; - break; - case DbType.Time: - if (value == null) value = null; - else value = ((TimeSpan)value).Ticks / 10000; - dbtype = DbType.Int64; - break; - } - var ret = new SQLiteParameter { ParameterName = QuoteParamterName(parameterName), DbType = dbtype, Value = value }; - _params?.Add(ret); - return ret; - } + public override DbParameter AppendParamter(List _params, string parameterName, Type type, object value) + { + if (string.IsNullOrEmpty(parameterName)) parameterName = $"p_{_params?.Count}"; + var dbtype = (DbType)_orm.CodeFirst.GetDbInfo(type)?.type; + switch (dbtype) + { + case DbType.Guid: + if (value == null) value = null; + else value = ((Guid)value).ToString(); + dbtype = DbType.String; + break; + case DbType.Time: + if (value == null) value = null; + else value = ((TimeSpan)value).Ticks / 10000; + dbtype = DbType.Int64; + break; + } + var ret = new SQLiteParameter { ParameterName = QuoteParamterName(parameterName), DbType = dbtype, Value = value }; + _params?.Add(ret); + return ret; + } - public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => - Utils.GetDbParamtersByObject(sql, obj, "@", (name, type, value) => { - var dbtype = (DbType)_orm.CodeFirst.GetDbInfo(type)?.type; - switch (dbtype) { - case DbType.Guid: - if (value == null) value = null; - else value = ((Guid)value).ToString(); - dbtype = DbType.String; - break; - case DbType.Time: - if (value == null) value = null; - else value = ((TimeSpan)value).Ticks / 10000; - dbtype = DbType.Int64; - break; - } - var ret = new SQLiteParameter { ParameterName = $"@{name}", DbType = dbtype, Value = value }; - return ret; - }); + public override DbParameter[] GetDbParamtersByObject(string sql, object obj) => + Utils.GetDbParamtersByObject(sql, obj, "@", (name, type, value) => + { + var dbtype = (DbType)_orm.CodeFirst.GetDbInfo(type)?.type; + switch (dbtype) + { + case DbType.Guid: + if (value == null) value = null; + else value = ((Guid)value).ToString(); + dbtype = DbType.String; + break; + case DbType.Time: + if (value == null) value = null; + else value = ((TimeSpan)value).Ticks / 10000; + dbtype = DbType.Int64; + break; + } + var ret = new SQLiteParameter { ParameterName = $"@{name}", DbType = dbtype, Value = value }; + return ret; + }); - public override string FormatSql(string sql, params object[] args) => sql?.FormatSqlite(args); - public override string QuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"\"{nametrim.Trim('"').Replace(".", "\".\"")}\""; - } - public override string TrimQuoteSqlName(string name) { - var nametrim = name.Trim(); - if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) - return nametrim; //原生SQL - return $"{nametrim.Trim('"').Replace("\".\"", ".").Replace(".\"", ".")}"; - } - public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; - public override string IsNull(string sql, object value) => $"ifnull({sql}, {value})"; - public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; - public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; + public override string FormatSql(string sql, params object[] args) => sql?.FormatSqlite(args); + public override string QuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"\"{nametrim.Trim('"').Replace(".", "\".\"")}\""; + } + public override string TrimQuoteSqlName(string name) + { + var nametrim = name.Trim(); + if (nametrim.StartsWith("(") && nametrim.EndsWith(")")) + return nametrim; //原生SQL + return $"{nametrim.Trim('"').Replace("\".\"", ".").Replace(".\"", ".")}"; + } + public override string QuoteParamterName(string name) => $"@{(_orm.CodeFirst.IsSyncStructureToLower ? name.ToLower() : name)}"; + public override string IsNull(string sql, object value) => $"ifnull({sql}, {value})"; + public override string StringConcat(string[] objs, Type[] types) => $"{string.Join(" || ", objs)}"; + public override string Mod(string left, string right, Type leftType, Type rightType) => $"{left} % {right}"; - public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; - public override string QuoteReadColumn(Type type, string columnName) => columnName; + public override string QuoteWriteParamter(Type type, string paramterName) => paramterName; + public override string QuoteReadColumn(Type type, string columnName) => columnName; - public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) { - if (value == null) return "NULL"; - if (type == typeof(byte[])) value = Encoding.UTF8.GetString(value as byte[]); - return FormatSql("{0}", value, 1); - } - } + public override string GetNoneParamaterSqlValue(List specialParams, Type type, object value) + { + if (value == null) return "NULL"; + if (type == typeof(byte[])) value = Encoding.UTF8.GetString(value as byte[]); + return FormatSql("{0}", value, 1); + } + } }